Commit d03e4b30 authored by zengqiang's avatar zengqiang

feat: H5提现功能对齐小程序实现

- 对齐后端api-jksxb-app和api-jksxb-mini的提现接口响应 - 修复提现列表页按钮显示逻辑,使用withdrawStatus判断WAIT_CONFIRM状态 - ProcessingStatus页面样式改用vw单位适配移动端 - 移除ProcessingStatus页面不应有的"去确认收款"按钮 - ProcessingStatus页面卡片文本对齐P3b设计文档 - ConfirmReceipt页面支持从列表页进入时获取packageInfo - 修复withdrawService接口类型定义(axios拦截器已解包)
parent abfbbfac
...@@ -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,13 @@ export interface WithdrawParams { ...@@ -85,10 +87,13 @@ 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;
} }
export interface WithdrawRiskResponse { export interface WithdrawRiskResponse {
......
...@@ -29,12 +29,12 @@ const routes: Array<RouteRecordRaw> = [ ...@@ -29,12 +29,12 @@ const routes: Array<RouteRecordRaw> = [
{ {
path: '/withdraw/confirm-receipt', path: '/withdraw/confirm-receipt',
name: 'WithdrawConfirmReceipt', name: 'WithdrawConfirmReceipt',
component: () => import('../views/withdraw/ConfirmReceipt.vue'), component: () => import('../views/withdraw/ConfirmReceipt.vue')
}, },
{ {
path: '/withdraw/processing-status', path: '/withdraw/processing-status',
name: 'WithdrawProcessingStatus', name: 'WithdrawProcessingStatus',
component: () => import('../views/withdraw/ProcessingStatus.vue'), component: () => import('../views/withdraw/ProcessingStatus.vue')
} }
] ]
......
import { post, get } from '../request'; import { get } from '../request'
interface WithdrawRequestData { interface WithdrawStatusResponseData {
withdrawNo: string;
amount: string; amount: string;
accountInfo: { withdrawStatus: string;
name: string; failReason?: string;
bank: string; withdrawApplyTime: string;
type: string; withdrawPayTime: string;
};
// Add other necessary fields as per backend API
}
interface WithdrawResponseData {
code: number;
message?: string;
data?: {
orderId: string;
packageInfo?: string; // For WeChat Pay H5 or other payment bridge data
};
} }
interface WithdrawStatusResponseData { interface WithdrawPackageInfoResponseData {
code: number; packageInfo: string;
message?: string; mchId: string;
data?: {
state: string; // e.g., PROCESSING, SUCCESS, FAILED
// Add other status details
};
} }
/** /**
* 发起提现申请 * 查询提现明细
* @param {WithdrawRequestData} data - 提现请求数据 * @param {string} withdrawNo - 提现流水号
* @returns {Promise<WithdrawResponseData>} * @returns {Promise<WithdrawStatusResponseData>}
*/ */
export function postWithdraw(data: WithdrawRequestData): Promise<WithdrawResponseData> { export function queryWithdrawStatus (withdrawNo: string): Promise<WithdrawStatusResponseData> {
return post( return get(
'/api-jksxb-h5/withdraw', `/api-jksxb-app/v1/withdraw/detail?withdrawNo=${withdrawNo}`
data, )
);
} }
/** /**
* 查询转账状态 * 获取提现确认参数
* @param {string} orderId - 订单ID * @param {string} withdrawNo - 提现流水号
* @returns {Promise<WithdrawStatusResponseData>} * @returns {Promise<WithdrawPackageInfoResponseData>}
*/ */
export function queryWithdrawStatus(orderId: string): Promise<WithdrawStatusResponseData> { export function getWithdrawPackageInfo (withdrawNo: string): Promise<WithdrawPackageInfoResponseData> {
return get( return get(
`/api-jksxb-h5/withdraw/status?orderId=${orderId}`, `/api-jksxb-app/v1/withdraw/packageInfo?withdrawNo=${withdrawNo}`
); )
} }
...@@ -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: '#fa8c16',
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,33 @@ const Withdraw = defineComponent({ ...@@ -134,9 +127,33 @@ 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 || ''
}
})
} 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)
// 新版流程:判断是否有 packageInfo
if (data.packageInfo) {
// 跳转到确认收款页
context.emit('withdrawSuccess', data)
} else {
// 无需确认,直接跳转到处理状态页
context.emit('withdrawSuccess', data) context.emit('withdrawSuccess', data)
}
} catch (err: any) { } catch (err: any) {
Toast(err) Toast(err)
} finally { } finally {
......
<template> <template>
<div class="container"> <div class="confirm-page">
<!-- 加载中 -->
<div class="info-card"> <div class="loading" v-if="loading">
<span class="label">提现金额</span> <span>加载中...</span>
<span class="value amount">¥ {{ amount }}</span>
</div> </div>
<div class="info-card"> <template v-else>
<div class="info-item"> <div class="confirm-icon">💰</div>
<span class="label">收款账户</span> <div class="confirm-title">提现申请已提交</div>
<span class="value">{{ accountInfo.name }} ({{ accountInfo.bank }})</span> <div class="confirm-amount">¥{{ amount }}</div>
</div>
<div class="info-item"> <div class="confirm-card">
<span class="label">账户类型</span> <p>请在微信中确认收款</p>
<span class="value">{{ accountInfo.type }}</span> <p>转账金额将在您确认后实时到账微信零钱</p>
</div> <p class="to-account" v-if="withdrawAccount">提现至:{{ withdrawAccount }}</p>
<p class="timeout-hint">⏰ 请在24小时内确认,超时将自动退回</p>
</div> </div>
<button class="confirm-button" @click="handleConfirm">确认提现</button> <button class="btn-confirm" @click="handleConfirm">👆 确认收款</button>
<button class="btn-back" @click="handleBack">返回奖励金首页</button>
<div class="footer-tip"> <div class="confirm-faq">
点击确认即表示您同意XXXX协议 <span class="faq-icon">?</span>
<span>点击后没反应?请更新微信至最新版本</span>
</div> </div>
</template>
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent } from 'vue'; import { defineComponent } from 'vue'
import { postWithdraw } from '@/server/api/withdrawService'; import { getWithdrawPackageInfo } from '@/server/api/withdrawService'
import { requestNativeMerchantTransfer } from '@/server/api/withdrawNativeService';
export default defineComponent({ export default defineComponent({
name: 'ConfirmReceipt', name: 'ConfirmReceipt',
data() { data () {
return { return {
amount: '0.00', amount: '0.00',
accountInfo: { withdrawNo: '',
name: '', withdrawAccount: '',
bank: '', packageInfo: '',
type: '', mchId: '',
}, loading: true
}; }
}, },
created() { async created () {
// In H5, parameters would typically come from route query or state management const query = this.$route.query
const query = this.$route.query; this.amount = (query.amount as string) || '0.00'
this.amount = (query.amount as string) || '0.00'; this.withdrawNo = (query.withdrawNo as string) || ''
try { this.withdrawAccount = query.withdrawAccount ? decodeURIComponent(query.withdrawAccount as string) : ''
this.accountInfo = JSON.parse(decodeURIComponent((query.accountInfo as string) || '{}'));
} catch (e) { if (query.packageInfo) {
console.error('Failed to parse accountInfo', e); // 场景1:从提现表单页进入,已有 packageInfo
this.accountInfo = { name: '', bank: '', type: '' }; this.packageInfo = decodeURIComponent(query.packageInfo as string)
this.mchId = (query.mchId as string) || ''
this.loading = false
} else if (this.withdrawNo) {
// 场景2:从列表页进入,需要查询 packageInfo
await this.fetchPackageInfo()
} else {
this.loading = false
} }
// H5 specific compatibility check or logic can go here if needed
// For now, we assume canUseMerchantTransfer is true for H5 context unless specific platform bridges are identified.
}, },
methods: { methods: {
async handleConfirm() { async fetchPackageInfo () {
try {
// const withdrawRes = await postWithdraw({
// amount: this.amount,
// accountInfo: this.accountInfo,
// });
// Placeholder for H5 specific payment logic
// This is where the "三端确认收款适配" (three-end confirm receipt adaptation) logic would reside.
// For H5 embedded in App, this might involve calling a JSBridge.
// For Official Account H5, this might involve redirecting to WeChat Pay H5.
// Since specifics are not provided, this will be a generic placeholder.
const withdrawRes = await postWithdraw({
amount: this.amount,
accountInfo: this.accountInfo,
});
if (withdrawRes.code === 0 && withdrawRes.data) {
const { orderId, packageInfo } = withdrawRes.data;
if (packageInfo) {
console.log('Processing packageInfo for H5 payment via JSBridge...', packageInfo);
try { try {
const nativeTransferRes = await requestNativeMerchantTransfer(packageInfo); console.log('fetchPackageInfo called, withdrawNo:', this.withdrawNo)
if (nativeTransferRes.errMsg === 'requestMerchantTransfer:ok') { const res = await getWithdrawPackageInfo(this.withdrawNo)
this.$router.replace({ console.log('packageInfo response:', JSON.stringify(res))
path: '/withdraw/processing-status', if (res) {
query: { status: 'WAIT_USER_CONFIRM', orderId: orderId }, this.packageInfo = res.packageInfo || ''
}); this.mchId = res.mchId || ''
console.log('packageInfo:', this.packageInfo, 'mchId:', this.mchId)
} else { } else {
alert(nativeTransferRes.errMsg || '用户取消或提现失败'); console.log('no data in response')
alert('获取提现信息失败')
} }
} catch (nativeError) { } catch (error) {
console.error('Native transfer request error:', nativeError); console.error('fetchPackageInfo error:', error)
alert((nativeError as Error).message || 'Native transfer failed, please retry.'); alert('网络请求失败: ' + error)
} finally {
this.loading = false
} }
} else { },
// Direct to processing status if no further payment step needed async handleConfirm () {
// H5 唤起用户确认收款弹窗 - 使用 alert 模拟
alert('H5确认收款功能:packageInfo=' + this.packageInfo + ', mchId=' + this.mchId)
// 模拟确认成功,跳转到处理状态页面
this.$router.replace({ this.$router.replace({
path: '/withdraw/processing-status', path: '/withdraw/processing-status',
query: { status: 'PROCESSING', orderId: orderId }, query: {
}); status: 'WAIT_CONFIRM',
withdrawNo: this.withdrawNo,
amount: this.amount
} }
} else { })
// Handle backend API error },
// this.$toast.fail(withdrawRes.message || '提现请求失败'); handleBack () {
alert(withdrawRes.message || '提现请求失败'); // Generic alert this.$router.replace({ path: '/' })
} }
} catch (error) {
console.error('Withdrawal request error:', error);
// this.$toast.fail(error.message || '网络请求失败,请稍后重试');
alert(error.message || '网络请求失败,请稍后重试'); // Generic alert
} finally {
// Hide loading indicator
// this.$toast.clear();
} }
}, })
},
});
</script> </script>
<style scoped> <style scoped>
.container { .confirm-page {
padding: 4vw; /* 30rpx = 4vw (30 * 0.1333) */ display: flex;
background-color: #f8f8f8; flex-direction: column;
align-items: center;
padding: 12vw 4vw;
text-align: center;
background: #ffffff;
min-height: 100vh; min-height: 100vh;
box-sizing: border-box; box-sizing: border-box;
} }
.info-card { .loading {
background-color: #ffffff; display: flex;
border-radius: 2.133vw; /* 16rpx */ align-items: center;
padding: 4vw; /* 30rpx */ justify-content: center;
margin-bottom: 2.666vw; /* 20rpx */ min-height: 50vh;
box-shadow: 0 0.266vw 1.333vw rgba(0, 0, 0, 0.05); /* 0 2rpx 10rpx */ color: #999;
font-size: 4vw;
} }
.info-card .label { .confirm-icon {
font-size: 3.733vw; /* 28rpx */ font-size: 10vw;
color: #888888; margin-bottom: 4vw;
margin-right: 2.666vw; /* 20rpx */
} }
.info-card .value { .confirm-title {
font-size: 3.733vw; /* 28rpx */ font-size: 5vw;
color: #333333; font-weight: 600;
color: #212121;
margin-bottom: 1vw;
} }
.info-card .amount { .confirm-amount {
font-size: 6.4vw; /* 48rpx */ font-size: 9vw;
font-weight: bold; font-weight: 700;
color: #333333; color: #212121;
display: block; margin-bottom: 8vw;
text-align: center; letter-spacing: -0.02em;
margin-top: 2.666vw; /* 20rpx */
} }
.info-item { .confirm-card {
display: flex; width: 100%;
justify-content: space-between; background: #f5f5f5;
align-items: center; border-radius: 3vw;
padding: 1.333vw 0; /* 10rpx */ padding: 4vw;
margin-bottom: 4vw;
box-sizing: border-box;
text-align: left;
} }
.info-item + .info-item { .confirm-card p {
border-top: 0.133vw solid #eee; /* 1rpx */ font-size: 3.5vw;
margin-top: 1.333vw; /* 10rpx */ color: #616161;
padding-top: 2.666vw; /* 20rpx */ line-height: 1.8;
margin: 0;
} }
.confirm-button { .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%; width: 100%;
height: 12vw; /* 90rpx */ padding: 4.5vw;
line-height: 12vw; /* 90rpx */ background: linear-gradient(135deg, #07c160 0%, #38cd7f 100%);
background-color: #07c160; color: white;
color: #ffffff; border: none;
font-size: 4.533vw; /* 34rpx */ border-radius: 3vw;
border-radius: 6vw; /* 45rpx */ font-size: 4vw;
margin-top: 5.333vw; /* 40rpx */ font-weight: 600;
border: none; /* Add border none for button */ margin-bottom: 3vw;
box-sizing: border-box;
cursor: pointer;
} }
.footer-tip { .btn-back {
text-align: center; width: 100%;
font-size: 3.2vw; /* 24rpx */ padding: 3.5vw;
color: #aaaaaa; background: #f5f5f5;
margin-top: 4vw; /* 30rpx */ 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> </style>
<template> <template>
<div class="container"> <div class="processing-page">
<img class="status-icon" :src="icon" mode="aspectFit" alt="Status Icon" /> <!-- Spinner -->
<p class="status-text" :class="statusClass">{{ statusText }}</p> <div class="spinner" v-if="!isFinalStatus"></div>
<div class="detail-card" v-if="orderId"> <!-- 标题 -->
<div class="detail-item"> <div class="processing-title">
<span class="label">订单号</span> {{ getTitleText }}
<span class="value">{{ orderId }}</span>
</div> </div>
<div class="detail-item">
<span class="label">当前状态</span> <!-- 金额 -->
<span class="value">{{ status }}</span> <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> </div>
</template>
</div> </div>
<button v-if="statusMap[status] && statusMap[status].action" class="action-button" @click="handleAction"> <!-- 提示 -->
{{ statusMap[status].action === 'confirm' ? '去确认收款' : '重新提现' }} <div class="processing-hint" v-if="!isFinalStatus">
</button> 自动查询状态中,请勿关闭
<div class="footer-tip">
如有疑问,请联系客服
</div> </div>
<!-- 按钮 -->
<button class="btn-back" @click="handleBackHome">返回首页</button>
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent } from 'vue'; import { defineComponent } from 'vue'
import { queryWithdrawStatus } from '@/server/api/withdrawService'; import { queryWithdrawStatus } from '@/server/api/withdrawService'
interface StatusConfig {
text: string;
icon: string;
action?: 'confirm' | 'retry';
}
interface StatusMap {
[key: string]: StatusConfig;
}
export default defineComponent({ export default defineComponent({
name: 'ProcessingStatus', name: 'ProcessingStatus',
data() { data () {
return { return {
status: 'PROCESSING', // PROCESSING, SUCCESS, FAIL, etc. status: 'TRANSFERING',
statusText: '提现处理中...', withdrawNo: '',
icon: '/assets/images/processing.png', // Placeholder for actual image path amount: '0.00',
orderId: '', failReason: '',
packageInfo: '',
mchId: '',
pollingInterval: null as ReturnType<typeof setInterval> | null, pollingInterval: null as ReturnType<typeof setInterval> | null,
pollingCount: 0, pollingCount: 0,
maxPollingAttempts: 10, maxPollingAttempts: 10
statusMap: { }
'ACCEPTED': { text: '提现处理中...', icon: '/assets/images/processing.png' }, },
'PROCESSING': { text: '提现处理中...', icon: '/assets/images/processing.png' }, computed: {
'WAIT_USER_CONFIRM': { text: '提现处理中,待用户确认收款', icon: '/assets/images/processing.png', action: 'confirm' }, isFinalStatus (): boolean {
'TRANSFERING': { text: '转账处理中...', icon: '/assets/images/processing.png' }, return ['RECEIVED', 'FAILED', 'CANCELLED'].includes(this.status)
'SUCCESS': { text: '提现成功', icon: '/assets/images/success.png' }, },
'FAILED': { text: '提现失败', icon: '/assets/images/fail.png', action: 'retry' }, getTitleText (): string {
'CANCELING': { text: '转账撤销中...', icon: '/assets/images/processing.png' }, if (this.isFinalStatus) {
'CANCELLED': { text: '转账已撤销', icon: '/assets/images/fail.png', action: 'retry' }, return this.status === 'RECEIVED' ? '提现成功' : '提现失败'
'UNKNOWN': { text: '状态未知,请稍后查询', icon: '/assets/images/processing.png' }, }
} as StatusMap, return '提现处理中'
}; }
}, },
created() { created () {
const query = this.$route.query; const query = this.$route.query
this.orderId = (query.orderId as string) || ''; this.withdrawNo = (query.withdrawNo as string) || ''
this.status = (query.status as string) || 'PROCESSING'; this.amount = (query.amount as string) || '0.00'
this.updateStatusDisplay(this.status); this.status = (query.status as string) || 'TRANSFERING'
this.packageInfo = query.packageInfo ? decodeURIComponent(query.packageInfo as string) : ''
this.mchId = (query.mchId as string) || ''
}, },
mounted() { mounted () {
this.startPolling(); this.startPolling()
}, },
beforeUnmount() { beforeUnmount () {
this.stopPolling(); this.stopPolling()
}, },
methods: { methods: {
updateStatusDisplay(statusCode: string) { startPolling () {
const displayStatus = this.statusMap[statusCode] || this.statusMap['UNKNOWN']; this.stopPolling()
this.statusText = displayStatus.text;
// Assuming image assets are in `/public/assets/images/` or handled by webpack aliasing
// For now, use relative path or direct path if assets are served from root
this.icon = displayStatus.icon.replace('/assets/images/', '/img/'); // Adjust path based on H5 asset structure
},
startPolling() {
this.stopPolling(); // Ensure no duplicate intervals
this.pollingInterval = setInterval(async () => { this.pollingInterval = setInterval(async () => {
this.pollingCount++; this.pollingCount++
if (this.pollingCount > this.maxPollingAttempts) { if (this.pollingCount > this.maxPollingAttempts) {
this.stopPolling(); this.stopPolling()
console.warn('Max polling attempts reached. Stopping polling.'); console.warn('Max polling attempts reached.')
this.updateStatusDisplay('UNKNOWN'); return
return;
} }
await this.queryTransferStatus(); await this.queryWithdrawStatus()
}, 5000); // Poll every 5 seconds }, 5000)
}, },
stopPolling() { stopPolling () {
if (this.pollingInterval) { if (this.pollingInterval) {
clearInterval(this.pollingInterval); clearInterval(this.pollingInterval)
this.pollingInterval = null; this.pollingInterval = null
} }
}, },
async queryTransferStatus() { async queryWithdrawStatus () {
if (!this.orderId) { if (!this.withdrawNo) {
console.error('No orderId available for status query.'); console.error('No withdrawNo available.')
this.stopPolling(); this.stopPolling()
return; return
} }
console.log(`Polling status for orderId: ${this.orderId}, attempt: ${this.pollingCount}`); console.log('Polling status for withdrawNo:', this.withdrawNo, 'attempt:', this.pollingCount)
try { try {
// const res = await queryWithdrawStatus(this.orderId); const res = await queryWithdrawStatus(this.withdrawNo)
if (res && res.withdrawStatus) {
const res = await queryWithdrawStatus(this.orderId); const newStatus = res.withdrawStatus
this.status = newStatus
if (res.code === 0 && res.data && res.data.state) { if (res.amount) {
const newStatus = res.data.state; this.amount = res.amount
this.status = newStatus; }
this.updateStatusDisplay(newStatus); if (res.failReason) {
this.failReason = res.failReason
if (['SUCCESS', 'FAILED', 'CANCELLED'].includes(newStatus)) { }
this.stopPolling(); if (['RECEIVED', 'FAILED', 'CANCELLED'].includes(newStatus)) {
this.stopPolling()
} }
} else {
console.error('Failed to query transfer status:', res.message || 'Unknown error');
} }
} catch (error) { } catch (error) {
console.error('Error querying transfer status:', error); console.error('Error querying status:', error)
} }
}, },
handleAction() { handleBackHome () {
const currentAction = this.statusMap[this.status]?.action; this.$router.replace({ path: '/' })
if (currentAction === 'confirm') {
// Navigate back to confirm page
this.$router.replace({ path: '/withdraw/confirm-receipt', query: { ...this.$route.query } });
} else if (currentAction === 'retry') {
// Navigate to withdrawal initiation page (placeholder)
this.$router.replace({ path: '/withdraw/initiate-withdrawal' });
} }
},
},
computed: {
statusClass(): string {
const currentStatus = this.status.toLowerCase();
if (['accepted', 'processing', 'transfering', 'unknown'].includes(currentStatus)) {
return 'status-processing';
} else if (currentStatus === 'wait_user_confirm') {
return 'status-wait-confirm';
} else if (currentStatus === 'success') {
return 'status-success';
} else if (['failed', 'cancelled'].includes(currentStatus)) {
return 'status-failed';
} }
return ''; })
},
},
});
</script> </script>
<style scoped> <style scoped>
.container { /* P3b 处理中页样式 - 基于 features/withdraw/prd/frontend-design/index.html */
.processing-page {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
padding: 8vw 4vw; /* 60rpx 30rpx */ padding: 12vw 4vw;
background-color: #f8f8f8; text-align: center;
background: #ffffff;
min-height: 100vh; min-height: 100vh;
box-sizing: border-box; box-sizing: border-box;
} }
.status-icon { .spinner {
width: 21.333vw; /* 160rpx */ width: 14vw;
height: 21.333vw; /* 160rpx */ height: 14vw;
margin-bottom: 5.333vw; /* 40rpx */ border: 1vw solid #eeeeee;
border-top-color: #07c160;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 6vw;
} }
.status-text { @keyframes spin {
font-size: 5.066vw; /* 38rpx */ to { transform: rotate(360deg); }
font-weight: bold;
color: #333333;
margin-bottom: 8vw; /* 60rpx */
text-align: center;
} }
.status-text.status-processing { .processing-title {
color: #1989fa; /* Blue for processing */ font-size: 5vw;
font-weight: 600;
color: #212121;
margin-bottom: 1vw;
} }
.status-text.status-wait-confirm { .processing-amount {
color: #ff976a; /* Orange for waiting confirmation */ font-size: 9vw;
font-weight: 700;
color: #212121;
margin-bottom: 8vw;
letter-spacing: -0.02em;
} }
.status-text.status-success { .processing-card {
color: #07c160; /* Green for success */ width: 100%;
background: #fafafa;
border-radius: 3vw;
padding: 6vw;
margin-bottom: 6vw;
box-sizing: border-box;
} }
.status-text.status-failed { .processing-card p {
color: #ee0a24; /* Red for failed/cancelled */ font-size: 3.5vw;
color: #616161;
line-height: 1.8;
margin: 0;
} }
.detail-card { .processing-card .to-account {
background-color: #ffffff; font-size: 3.2vw;
border-radius: 2.133vw; /* 16rpx */ color: #9e9e9e;
padding: 4vw; /* 30rpx */ margin-top: 2vw;
width: 100%;
max-width: 80vw; /* Approx 600rpx */
box-shadow: 0 0.266vw 1.333vw rgba(0, 0, 0, 0.05); /* 0 2rpx 10rpx */
margin-bottom: 8vw; /* 60rpx */
} }
.detail-item { .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; display: flex;
justify-content: space-between; align-items: center;
padding: 1.333vw 0; /* 10rpx */ justify-content: center;
font-size: 3.733vw; /* 28rpx */ gap: 1vw;
color: #555555;
} }
.detail-item + .detail-item { .processing-hint::before {
border-top: 0.133vw solid #eee; /* 1rpx */ content: '';
margin-top: 1.333vw; /* 10rpx */ width: 1.5vw;
padding-top: 2.666vw; /* 20rpx */ height: 1.5vw;
background: #07c160;
border-radius: 50%;
animation: pulse 1s ease-in-out infinite;
} }
.detail-item .label { @keyframes pulse {
color: #888888; 0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(1.2); }
} }
.action-button { .btn-back {
width: 100%; width: 100%;
max-width: 80vw; /* Approx 600rpx */ padding: 3.5vw;
height: 12vw; /* 90rpx */ background: #f5f5f5;
line-height: 12vw; /* 90rpx */ color: #757575;
background-color: #07c160; border: none;
color: #ffffff; border-radius: 3vw;
font-size: 4.533vw; /* 34rpx */ font-size: 3.5vw;
border-radius: 6vw; /* 45rpx */ font-weight: 500;
margin-top: 5.333vw; /* 40rpx */ box-sizing: border-box;
border: none; /* Add border none for button */ cursor: pointer;
}
.footer-tip {
text-align: center;
font-size: 3.2vw; /* 24rpx */
color: #aaaaaa;
margin-top: 8vw; /* 60rpx */
} }
</style> </style>
import { mount, flushPromises } from '@vue/test-utils'; import { mount } from '@vue/test-utils';
import ConfirmReceipt from '../ConfirmReceipt.vue'; import ConfirmReceipt from '../ConfirmReceipt.vue';
import { postWithdraw } from '@/server/api/withdrawService';
import { requestNativeMerchantTransfer } from '@/server/api/withdrawNativeService';
// Mock vue-router // Mock vue-router
const mockRouter = { const mockRouter = {
...@@ -10,13 +8,13 @@ const mockRouter = { ...@@ -10,13 +8,13 @@ const mockRouter = {
const mockRoute = { const mockRoute = {
query: { query: {
amount: '100.00', amount: '100.00',
accountInfo: encodeURIComponent(JSON.stringify({ name: 'Test User', bank: 'Test Bank', type: 'Debit' })), withdrawNo: 'WD123456',
withdrawAccount: encodeURIComponent('微信用户'),
packageInfo: encodeURIComponent('test_package'),
mchId: 'test_mch_id',
}, },
}; };
jest.mock('@/server/api/withdrawService');
jest.mock('@/server/api/withdrawNativeService');
describe('ConfirmReceipt.vue', () => { describe('ConfirmReceipt.vue', () => {
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
...@@ -32,16 +30,12 @@ describe('ConfirmReceipt.vue', () => { ...@@ -32,16 +30,12 @@ describe('ConfirmReceipt.vue', () => {
}, },
}); });
expect(wrapper.find('.amount').text()).toBe('¥ 100.00'); expect(wrapper.find('.confirm-amount').text()).toBe('¥100.00');
expect(wrapper.findAll('.info-item .value')[0].text()).toBe('Test User (Test Bank)'); expect(wrapper.find('.confirm-title').text()).toBe('提现申请已提交');
expect(wrapper.findAll('.info-item .value')[1].text()).toBe('Debit');
}); });
it('calls postWithdraw and redirects to processing status on success without packageInfo', async () => { it('shows alert and navigates to processing-status on confirm click', () => {
(postWithdraw as jest.Mock).mockResolvedValueOnce({ const alertSpy = jest.spyOn(window, 'alert').mockImplementation(() => {});
code: 0,
data: { orderId: 'ORDER123', packageInfo: null },
});
const wrapper = mount(ConfirmReceipt, { const wrapper = mount(ConfirmReceipt, {
global: { global: {
...@@ -52,96 +46,22 @@ describe('ConfirmReceipt.vue', () => { ...@@ -52,96 +46,22 @@ describe('ConfirmReceipt.vue', () => {
}, },
}); });
wrapper.find('.confirm-button').trigger('click'); wrapper.find('.btn-confirm').trigger('click');
await flushPromises();
expect(postWithdraw).toHaveBeenCalledTimes(1); expect(alertSpy).toHaveBeenCalled();
expect(postWithdraw).toHaveBeenCalledWith({
amount: '100.00',
accountInfo: { name: 'Test User', bank: 'Test Bank', type: 'Debit' },
});
expect(mockRouter.replace).toHaveBeenCalledTimes(1);
expect(mockRouter.replace).toHaveBeenCalledWith({ expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/processing-status', path: '/withdraw/processing-status',
query: { status: 'PROCESSING', orderId: 'ORDER123' }, query: {
}); status: 'WAIT_CONFIRM',
}); withdrawNo: 'WD123456',
it('calls postWithdraw, then requestNativeMerchantTransfer, and redirects to processing status with WAIT_USER_CONFIRM if packageInfo is present and native call succeeds', async () => {
(postWithdraw as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { orderId: 'ORDER456', packageInfo: 'some_package_info_string' },
});
(requestNativeMerchantTransfer as jest.Mock).mockResolvedValueOnce({
errMsg: 'requestMerchantTransfer:ok',
});
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.find('.confirm-button').trigger('click');
await flushPromises();
expect(postWithdraw).toHaveBeenCalledTimes(1);
expect(postWithdraw).toHaveBeenCalledWith({
amount: '100.00', amount: '100.00',
accountInfo: { name: 'Test User', bank: 'Test Bank', type: 'Debit' },
});
expect(requestNativeMerchantTransfer).toHaveBeenCalledTimes(1);
expect(requestNativeMerchantTransfer).toHaveBeenCalledWith('some_package_info_string');
expect(mockRouter.replace).toHaveBeenCalledTimes(1);
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/processing-status',
query: { status: 'WAIT_USER_CONFIRM', orderId: 'ORDER456' },
});
});
it('handles native transfer error when packageInfo is present', async () => {
(postWithdraw as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { orderId: 'ORDER789', packageInfo: 'some_package_info_string' },
});
(requestNativeMerchantTransfer as jest.Mock).mockRejectedValueOnce(new Error('Native transfer error'));
const alertSpy = jest.spyOn(window, 'alert').mockImplementation(() => {});
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
}, },
}); });
wrapper.find('.confirm-button').trigger('click');
await flushPromises();
expect(postWithdraw).toHaveBeenCalledTimes(1);
expect(requestNativeMerchantTransfer).toHaveBeenCalledTimes(1);
expect(alertSpy).toHaveBeenCalledWith('Native transfer error');
expect(mockRouter.replace).not.toHaveBeenCalled();
alertSpy.mockRestore(); alertSpy.mockRestore();
}); });
it('handles native transfer cancellation/failure when packageInfo is present', async () => { it('navigates back on back button click', () => {
(postWithdraw as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { orderId: 'ORDER901', packageInfo: 'some_package_info_string' },
});
(requestNativeMerchantTransfer as jest.Mock).mockResolvedValueOnce({
errMsg: 'requestMerchantTransfer:fail user cancel',
});
const alertSpy = jest.spyOn(window, 'alert').mockImplementation(() => {});
const wrapper = mount(ConfirmReceipt, { const wrapper = mount(ConfirmReceipt, {
global: { global: {
mocks: { mocks: {
...@@ -151,14 +71,10 @@ describe('ConfirmReceipt.vue', () => { ...@@ -151,14 +71,10 @@ describe('ConfirmReceipt.vue', () => {
}, },
}); });
wrapper.find('.confirm-button').trigger('click'); wrapper.find('.btn-back').trigger('click');
await flushPromises();
expect(postWithdraw).toHaveBeenCalledTimes(1);
expect(requestNativeMerchantTransfer).toHaveBeenCalledTimes(1);
expect(alertSpy).toHaveBeenCalledWith('requestMerchantTransfer:fail user cancel');
expect(mockRouter.replace).not.toHaveBeenCalled();
alertSpy.mockRestore(); expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/bonus/withdraw',
});
}); });
}); });
...@@ -8,8 +8,9 @@ const mockRouter = { ...@@ -8,8 +8,9 @@ const mockRouter = {
}; };
const mockRoute = { const mockRoute = {
query: { query: {
orderId: 'ORDER789', withdrawNo: 'WD123456',
status: 'PROCESSING', amount: '100.00',
status: 'TRANSFERING',
}, },
}; };
...@@ -21,7 +22,7 @@ describe('ProcessingStatus.vue', () => { ...@@ -21,7 +22,7 @@ describe('ProcessingStatus.vue', () => {
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
setIntervalSpy = jest.spyOn(window, 'setInterval').mockReturnValue(123 as any); // Mock interval ID setIntervalSpy = jest.spyOn(window, 'setInterval').mockReturnValue(123 as any);
clearIntervalSpy = jest.spyOn(window, 'clearInterval'); clearIntervalSpy = jest.spyOn(window, 'clearInterval');
}); });
...@@ -30,7 +31,7 @@ describe('ProcessingStatus.vue', () => { ...@@ -30,7 +31,7 @@ describe('ProcessingStatus.vue', () => {
clearIntervalSpy.mockRestore(); clearIntervalSpy.mockRestore();
}); });
it('renders correctly with initial data and starts polling', () => { it('renders correctly with initial data', () => {
const wrapper = mount(ProcessingStatus, { const wrapper = mount(ProcessingStatus, {
global: { global: {
mocks: { mocks: {
...@@ -40,59 +41,41 @@ describe('ProcessingStatus.vue', () => { ...@@ -40,59 +41,41 @@ describe('ProcessingStatus.vue', () => {
}, },
}); });
expect(wrapper.find('.status-text').text()).toBe('提现处理中...'); expect(wrapper.find('.processing-title').text()).toBe('提现处理中');
expect(wrapper.find('.detail-item .value').text()).toBe('ORDER789'); expect(wrapper.find('.processing-amount').text()).toBe('¥100.00');
expect(setIntervalSpy).toHaveBeenCalledTimes(1); expect(wrapper.find('.spinner').exists()).toBe(true);
expect(clearIntervalSpy).toHaveBeenCalledTimes(0); // No clearInterval on initial mount as pollingInterval is null
}); });
it('stops polling on unmount', () => { it('shows success state without spinner', () => {
const wrapper = mount(ProcessingStatus, { const wrapper = mount(ProcessingStatus, {
global: { global: {
mocks: { mocks: {
$route: mockRoute, $route: { query: { withdrawNo: 'WD123456', amount: '100.00', status: 'RECEIVED' } },
$router: mockRouter, $router: mockRouter,
}, },
}, },
}); });
wrapper.unmount(); expect(wrapper.find('.processing-title').text()).toBe('提现成功');
expect(clearIntervalSpy).toHaveBeenCalledTimes(1); // One from unmount expect(wrapper.find('.spinner').exists()).toBe(false);
expect(clearIntervalSpy).toHaveBeenCalledWith(123);
});
it('updates status display based on API response and stops polling on success', async () => {
(queryWithdrawStatus as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { state: 'SUCCESS' },
}); });
it('shows failed state without spinner', () => {
const wrapper = mount(ProcessingStatus, { const wrapper = mount(ProcessingStatus, {
global: { global: {
mocks: { mocks: {
$route: mockRoute, $route: { query: { withdrawNo: 'WD123456', amount: '100.00', status: 'FAILED' } },
$router: mockRouter, $router: mockRouter,
}, },
}, },
}); });
// Manually trigger polling interval logic expect(wrapper.find('.processing-title').text()).toBe('提现失败');
// The setInterval is mocked, so we need to manually call the handler expect(wrapper.find('.spinner').exists()).toBe(false);
await (wrapper.vm as any).queryTransferStatus();
await flushPromises();
expect(wrapper.find('.status-text').text()).toBe('提现成功');
expect(wrapper.vm.status).toBe('SUCCESS');
expect(clearIntervalSpy).toHaveBeenCalledTimes(1); // One after success
});
it('updates status display based on API response and stops polling on failed', async () => {
(queryWithdrawStatus as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { state: 'FAILED' },
}); });
const wrapper = mount(ProcessingStatus, { it('starts polling on mount', () => {
mount(ProcessingStatus, {
global: { global: {
mocks: { mocks: {
$route: mockRoute, $route: mockRoute,
...@@ -101,120 +84,29 @@ describe('ProcessingStatus.vue', () => { ...@@ -101,120 +84,29 @@ describe('ProcessingStatus.vue', () => {
}, },
}); });
await (wrapper.vm as any).queryTransferStatus(); expect(setIntervalSpy).toHaveBeenCalledTimes(1);
await flushPromises();
expect(wrapper.find('.status-text').text()).toBe('提现失败');
expect(wrapper.vm.status).toBe('FAILED');
expect(clearIntervalSpy).toHaveBeenCalledTimes(1); // One after failed
});
it('applies "status-processing" class for PROCESSING status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'PROCESSING' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-processing');
});
it('applies "status-wait-confirm" class for WAIT_USER_CONFIRM status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'WAIT_USER_CONFIRM' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-wait-confirm');
});
it('applies "status-success" class for SUCCESS status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'SUCCESS' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-success');
});
it('applies "status-failed" class for FAILED status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'FAILED' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-failed');
});
it('applies "status-failed" class for CANCELLED status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'CANCELLED' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-failed');
}); });
it('redirects to confirm-receipt on handleAction when status is WAIT_USER_CONFIRM', async () => { it('stops polling on unmount', () => {
const wrapper = mount(ProcessingStatus, { const wrapper = mount(ProcessingStatus, {
global: { global: {
mocks: { mocks: {
$route: { query: { orderId: 'ORDER789', status: 'WAIT_USER_CONFIRM' } }, $route: mockRoute,
$router: mockRouter, $router: mockRouter,
}, },
}, },
}); });
await wrapper.vm.$nextTick(); // Wait for data to be set up wrapper.unmount();
wrapper.find('.action-button').trigger('click'); expect(clearIntervalSpy).toHaveBeenCalled();
await flushPromises();
expect(mockRouter.replace).toHaveBeenCalledTimes(1);
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/confirm-receipt',
query: { orderId: 'ORDER789', status: 'WAIT_USER_CONFIRM' },
});
});
it('redirects to initiate-withdrawal on handleAction when status is FAILED (retry)', async () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'FAILED' } },
$router: mockRouter,
},
},
}); });
await wrapper.vm.$nextTick(); // Wait for data to be set up it('updates status on API response', async () => {
wrapper.find('.action-button').trigger('click'); (queryWithdrawStatus as jest.Mock).mockResolvedValueOnce({
await flushPromises(); code: 0,
data: { withdrawStatus: 'RECEIVED', amount: '100.00' },
expect(mockRouter.replace).toHaveBeenCalledTimes(1);
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/initiate-withdrawal',
});
}); });
it('handles API error during polling', async () => {
(queryWithdrawStatus as jest.Mock).mockRejectedValueOnce(new Error('Network error during polling'));
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
const wrapper = mount(ProcessingStatus, { const wrapper = mount(ProcessingStatus, {
global: { global: {
mocks: { mocks: {
...@@ -224,25 +116,13 @@ describe('ProcessingStatus.vue', () => { ...@@ -224,25 +116,13 @@ describe('ProcessingStatus.vue', () => {
}, },
}); });
await (wrapper.vm as any).queryTransferStatus(); await (wrapper.vm as any).queryWithdrawStatus();
await flushPromises(); await flushPromises();
expect(consoleErrorSpy).toHaveBeenCalledWith('Error querying transfer status:', expect.any(Error)); expect(wrapper.vm.status).toBe('RECEIVED');
expect(wrapper.vm.status).toBe('PROCESSING'); // Status should remain unchanged or go to UNKNOWN after max attempts
// Polling continues until max attempts or terminal state is reached
consoleErrorSpy.mockRestore();
});
it('handles non-successful API response during polling', async () => {
(queryWithdrawStatus as jest.Mock).mockResolvedValueOnce({
code: 1, // Non-zero code
message: 'Transfer status query failed',
data: null,
}); });
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); it('navigates back to withdraw page on button click', () => {
const wrapper = mount(ProcessingStatus, { const wrapper = mount(ProcessingStatus, {
global: { global: {
mocks: { mocks: {
...@@ -252,14 +132,10 @@ describe('ProcessingStatus.vue', () => { ...@@ -252,14 +132,10 @@ describe('ProcessingStatus.vue', () => {
}, },
}); });
await (wrapper.vm as any).queryTransferStatus(); wrapper.find('.btn-back').trigger('click');
await flushPromises();
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Failed to query transfer status:', 'Transfer status query failed'
);
expect(wrapper.vm.status).toBe('PROCESSING'); // Status should remain unchanged
consoleErrorSpy.mockRestore(); expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/bonus/withdraw',
});
}); });
}); });
...@@ -13,7 +13,7 @@ const { getPublicPath, Plugin: WebpackUploadAssetsPlugin } = createUploadAssetsP ...@@ -13,7 +13,7 @@ const { getPublicPath, Plugin: WebpackUploadAssetsPlugin } = createUploadAssetsP
console.log('upload assets to cdn', shouldUploadAssetsToCdn) console.log('upload assets to cdn', shouldUploadAssetsToCdn)
const proxyUrl = 'https://geek.jkwljy.com' const proxyUrl = 'http://172.16.62.125'
const proxyOptions = { const proxyOptions = {
target: proxyUrl, target: proxyUrl,
......
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