fix: 收口退款鉴权、核销目标和微信退款占额
管理员退款只认管理员令牌。通用核销锁定具体票据,同码多目标时拒绝。已结算订单不再覆盖退款状态。微信退款先落库并占用处理中额度,未到账不把订单标成已退款。
这个提交包含在:
@@ -95,7 +95,7 @@
|
|||||||
<template v-else-if="order.status === 'IN_SERVICE'">
|
<template v-else-if="order.status === 'IN_SERVICE'">
|
||||||
<button class="action-btn chat-btn btn-active" @click="contactExpert(order)">联系客服</button>
|
<button class="action-btn chat-btn btn-active" @click="contactExpert(order)">联系客服</button>
|
||||||
<button class="action-btn refund-btn btn-active" @click="openRefundModal(order)">申请退款</button>
|
<button class="action-btn refund-btn btn-active" @click="openRefundModal(order)">申请退款</button>
|
||||||
<button class="action-btn success-btn btn-active" @click="confirmComplete(order.id)">确认验收</button>
|
<button v-if="order.rawStatus === '待确认'" class="action-btn success-btn btn-active" @click="confirmComplete(order.id)">确认验收</button>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template v-else-if="order.status === 'COMPLETED'">
|
<template v-else-if="order.status === 'COMPLETED'">
|
||||||
@@ -598,15 +598,18 @@ const payOrder = async (id) => {
|
|||||||
scene: 'ORDER',
|
scene: 'ORDER',
|
||||||
userId: uid
|
userId: uid
|
||||||
});
|
});
|
||||||
await payOrderApi(id, {
|
const paid = await payOrderApi(id, {
|
||||||
targetStatus: '履约中',
|
|
||||||
payType: 'WECHAT',
|
payType: 'WECHAT',
|
||||||
buyerId: uid
|
buyerId: uid
|
||||||
});
|
});
|
||||||
uni.hideLoading();
|
uni.hideLoading();
|
||||||
applyOrderStatus(o, 'IN_SERVICE');
|
const nextStatus = paid && paid.status ? paid.status : 'IN_SERVICE';
|
||||||
if (o) o.rawStatus = '履约中';
|
applyOrderStatus(o, nextStatus);
|
||||||
uni.showToast({ title: '支付成功,服务已开始', icon: 'success' });
|
if (o) o.rawStatus = (paid && paid.rawStatus) || (nextStatus === 'PENDING_ACCEPT' ? '待接单' : '履约中');
|
||||||
|
uni.showToast({
|
||||||
|
title: nextStatus === 'PENDING_ACCEPT' ? '支付成功,等待大神接单' : '支付成功,服务已开始',
|
||||||
|
icon: 'success'
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
uni.hideLoading();
|
uni.hideLoading();
|
||||||
if (err && err.cancelled) {
|
if (err && err.cancelled) {
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/** 已退金额加上处理中的微信退款,再加上本次申请,不得超过订单金额。 */
|
||||||
|
export function canReserveRefund(
|
||||||
|
amountCents: number,
|
||||||
|
refundedCents: number,
|
||||||
|
pendingOtherCents: number,
|
||||||
|
requestCents: number
|
||||||
|
): boolean {
|
||||||
|
if (!(requestCents > 0)) return false;
|
||||||
|
return refundedCents + pendingOtherCents + requestCents <= amountCents;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本次退款应从一笔已入账佣金里扣回的金额。按「退款 / 退款前仍留在平台的订单金额」计算,避免剩余结算后再退时少扣。 */
|
||||||
|
export function clawbackDelta(
|
||||||
|
credit: number,
|
||||||
|
alreadyClawed: number,
|
||||||
|
orderAmount: number,
|
||||||
|
alreadyRefunded: number,
|
||||||
|
refund: number
|
||||||
|
): number {
|
||||||
|
const room = Number((Number(credit || 0) - Number(alreadyClawed || 0)).toFixed(2));
|
||||||
|
if (!(room > 0) || !(Number(refund) > 0)) return 0;
|
||||||
|
const retainedBefore = Number((Number(orderAmount || 0) - Number(alreadyRefunded || 0)).toFixed(2));
|
||||||
|
if (!(retainedBefore > 0)) return room;
|
||||||
|
const fraction = Math.min(1, Number(refund) / retainedBefore);
|
||||||
|
if (fraction >= 1 - 1e-9) return room;
|
||||||
|
return Number(Math.min(room, room * fraction).toFixed(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 入账类型可能是「一级分销佣金」或「一级分销佣金 (5%)」。 */
|
||||||
|
export function payoutClawbackKind(type: string): 'expert' | 'referral1' | 'referral2' | null {
|
||||||
|
const t = String(type || '');
|
||||||
|
if (t === '大神完单收益结算' || t === '仲裁部分结算' || t === '部分退款剩余结算') return 'expert';
|
||||||
|
if (t.startsWith('一级分销佣金')) return 'referral1';
|
||||||
|
if (t.startsWith('二级分销佣金')) return 'referral2';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wechatRefundCounterparty(outRefundNo: string): string {
|
||||||
|
return `微信支付原路退款:${outRefundNo}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 同一笔逻辑退款使用稳定单号,便于受理中重试;不同金额或不同已退进度使用不同单号。 */
|
||||||
|
export function buildOutRefundNo(tag: string, orderId: string, priorCents: number, refundCents: number): string {
|
||||||
|
const clean = `${tag}_${orderId}_${priorCents}_${refundCents}`.replace(/[^A-Za-z0-9_]/g, '');
|
||||||
|
if (clean.length >= 6 && clean.length <= 64) return clean;
|
||||||
|
let hash = 0;
|
||||||
|
for (let i = 0; i < clean.length; i += 1) hash = (hash * 33 + clean.charCodeAt(i)) >>> 0;
|
||||||
|
const head = String(tag || 'RFND').replace(/[^A-Za-z0-9_]/g, '').slice(0, 12) || 'RFND';
|
||||||
|
return `${head}_${hash.toString(16)}_${priorCents}_${refundCents}`.slice(0, 64);
|
||||||
|
}
|
||||||
@@ -6,8 +6,12 @@
|
|||||||
export interface WeChatRefundResult {
|
export interface WeChatRefundResult {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
skipped?: boolean;
|
skipped?: boolean;
|
||||||
|
/** 微信已受理但尚未到账。此时不得把订单标成已退款。 */
|
||||||
|
pending?: boolean;
|
||||||
status?: string;
|
status?: string;
|
||||||
refundId?: string;
|
refundId?: string;
|
||||||
|
/** 实际提交给微信的退款单号。失败重试时可能带后缀,记账必须用这个值。 */
|
||||||
|
outRefundNo?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
文件差异内容过多而无法显示
加载差异
@@ -27,6 +27,7 @@ import {
|
|||||||
transferToWallet,
|
transferToWallet,
|
||||||
queryTransferByOutBillNo,
|
queryTransferByOutBillNo,
|
||||||
createRefund,
|
createRefund,
|
||||||
|
queryRefundByOutRefundNo,
|
||||||
} from './core/pay/wechat-pay-v3';
|
} from './core/pay/wechat-pay-v3';
|
||||||
import { sendSubscribeMessageHttp, buildTemplateData } from './core/notify/wechat-subscribe.service';
|
import { sendSubscribeMessageHttp, buildTemplateData } from './core/notify/wechat-subscribe.service';
|
||||||
import { setWeChatRefundFn } from './core/pay/refund-bridge';
|
import { setWeChatRefundFn } from './core/pay/refund-bridge';
|
||||||
@@ -1241,7 +1242,7 @@ app.post('/api/activities/all/verify', async (req: Request, res: Response) => {
|
|||||||
try {
|
try {
|
||||||
const { operatorId, verifyCode } = req.body;
|
const { operatorId, verifyCode } = req.body;
|
||||||
let operator = resolveSecureUserId(req, Number(operatorId || 0), '核销组局门票');
|
let operator = resolveSecureUserId(req, Number(operatorId || 0), '核销组局门票');
|
||||||
const result = await repo.universalVerifyCheckin(String(verifyCode), operator);
|
const result = await repo.universalVerifyCheckin(String(verifyCode), operator, isVerifiedAdminRequest(req));
|
||||||
res.json({ code: 20000, data: result, message: '核销成功,已完成现场到场签到' });
|
res.json({ code: 20000, data: result, message: '核销成功,已完成现场到场签到' });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
const statusCode = err.status || 400;
|
const statusCode = err.status || 400;
|
||||||
@@ -1302,21 +1303,8 @@ app.post('/api/verify/universal', async (req: Request, res: Response) => {
|
|||||||
try {
|
try {
|
||||||
const { verifyCode, operatorId } = req.body;
|
const { verifyCode, operatorId } = req.body;
|
||||||
const operator = resolveSecureUserId(req, Number(operatorId || 0), '核销门票');
|
const operator = resolveSecureUserId(req, Number(operatorId || 0), '核销门票');
|
||||||
// 校验核销人归属:活动门票仅限发起人核销;订单门票仅限承接大神核销(不依赖 NODE_ENV)
|
// 仓储在事务内按操作人筛选并锁定唯一票据,避免全局撞码造成误拒绝。
|
||||||
if (SECURE_MODE && !isVerifiedAdminRequest(req)) {
|
const result = await repo.universalVerifyCheckin(String(verifyCode), operator, isVerifiedAdminRequest(req));
|
||||||
const info = await repo.queryCheckinCodeInfo(String(verifyCode));
|
|
||||||
let allowed = false;
|
|
||||||
if (info.type === 'ACTIVITY') {
|
|
||||||
allowed = Number(info.creatorId) === operator;
|
|
||||||
} else if (info.type === 'ORDER') {
|
|
||||||
const own = await repo.getOrderOwnership(String(info.id));
|
|
||||||
allowed = Boolean(own) && own!.companionIds.includes(operator);
|
|
||||||
}
|
|
||||||
if (!allowed) {
|
|
||||||
return res.status(403).json({ code: 40300, message: '无权核销该门票(非活动发起人或承接大神)' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const result = await repo.universalVerifyCheckin(String(verifyCode), operator);
|
|
||||||
res.json({
|
res.json({
|
||||||
code: 20000,
|
code: 20000,
|
||||||
data: result,
|
data: result,
|
||||||
@@ -2517,7 +2505,7 @@ app.post('/api/orders/:id/cancel', async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
// 买家取消:按状态安全处理(已付款待接单会原路退款;已进入履约需走退款申诉),避免静默吞掉已付款资金
|
// 买家取消:按状态安全处理(已付款待接单会原路退款;已进入履约需走退款申诉),避免静默吞掉已付款资金
|
||||||
const order = role.isAdmin
|
const order = role.isAdmin
|
||||||
? await repo.updateOrderStatus(orderId, '已取消')
|
? await repo.adminCancelOrder(orderId)
|
||||||
: await repo.buyerCancelOrder(orderId);
|
: await repo.buyerCancelOrder(orderId);
|
||||||
res.json({ code: 20000, data: order, message: '订单已取消' });
|
res.json({ code: 20000, data: order, message: '订单已取消' });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -2591,16 +2579,22 @@ app.post('/api/orders/:id/pay', async (req: Request, res: Response) => {
|
|||||||
return res.status(403).json({ code: 40300, message: '支付未通过服务端收款确认,禁止直接变更订单支付状态' });
|
return res.status(403).json({ code: 40300, message: '支付未通过服务端收款确认,禁止直接变更订单支付状态' });
|
||||||
}
|
}
|
||||||
|
|
||||||
// 沙箱仅允许推进到「已支付待履约」的合法状态,严禁客户端任意指定终态或退款态
|
// 沙箱只接受合法已支付状态。派单订单一律待接单,客户端不能把派单推进到履约中。
|
||||||
const requested = String(req.body?.targetStatus || (Number(own.expertId) ? '履约中' : '待接单'));
|
const requested = String(req.body?.targetStatus || '履约中');
|
||||||
const allowedSandboxStatuses = ['履约中', '待接单'];
|
const allowedSandboxStatuses = ['履约中', '待接单'];
|
||||||
if (!allowedSandboxStatuses.includes(requested)) {
|
if (!allowedSandboxStatuses.includes(requested)) {
|
||||||
return res.status(400).json({ code: 40000, message: `非法的目标订单状态: ${requested}` });
|
return res.status(400).json({ code: 40000, message: '不支持的支付后状态' });
|
||||||
}
|
}
|
||||||
const order = await repo.updateOrderStatus(orderId, requested);
|
const isMarketplace = !Number(own.expertId);
|
||||||
if (requested === '待接单') void notifyNearbyExpertsForOrder(order);
|
const paidStatus = isMarketplace ? '待接单' : '履约中';
|
||||||
|
const order = await repo.updateOrderStatus(orderId, paidStatus);
|
||||||
const buyer = Number(own.buyerId || 0);
|
const buyer = Number(own.buyerId || 0);
|
||||||
pushUserNotification(buyer, 'ORDER_STATUS', '订单已开始服务', `订单 ${order?.order_no || orderId} 已进入${requested}${order?.verify_code ? `,核销码 ${order.verify_code}` : ''},请按时到场。`, '/pages/order/list');
|
if (paidStatus === '待接单') {
|
||||||
|
void notifyNearbyExpertsForOrder(order);
|
||||||
|
pushUserNotification(buyer, 'ORDER_STATUS', '支付成功,等待大神接单', `订单 ${order?.order_no || orderId} 已支付,正在为您匹配附近大神;30 分钟内无人接单将自动全额退款。`, '/pages/order/list');
|
||||||
|
return res.json({ code: 20000, data: order, message: '支付成功,已进入派单池,等待附近大神接单' });
|
||||||
|
}
|
||||||
|
pushUserNotification(buyer, 'ORDER_STATUS', '订单已开始服务', `订单 ${order?.order_no || orderId} 已进入履约中${order?.verify_code ? `,核销码 ${order.verify_code}` : ''},请按时到场。`, '/pages/order/list');
|
||||||
void notifyBySubscribe('orderStatus', {
|
void notifyBySubscribe('orderStatus', {
|
||||||
userId: buyer,
|
userId: buyer,
|
||||||
page: '/pages/order/list',
|
page: '/pages/order/list',
|
||||||
@@ -2611,7 +2605,7 @@ app.post('/api/orders/:id/pay', async (req: Request, res: Response) => {
|
|||||||
thing4: order?.verify_code ? `核销码${order.verify_code},请出示` : '请按时到场,感谢支持'
|
thing4: order?.verify_code ? `核销码${order.verify_code},请出示` : '请按时到场,感谢支持'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
res.json({ code: 20000, data: order, message: `支付成功,订单已进入${requested}` });
|
res.json({ code: 20000, data: order, message: '支付成功,订单已进入履约中' });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
const statusCode = err.status || 400;
|
const statusCode = err.status || 400;
|
||||||
const errCode = err.code || 40000;
|
const errCode = err.code || 40000;
|
||||||
@@ -3140,39 +3134,111 @@ async function notifyBySubscribe(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 注册微信原路退款执行器(供仓储层退款时调用;未就绪时返回 skipped,由调用方回退余额退款)
|
function wechatRefundResult(status: string, outRefundNo: string, refundId?: string) {
|
||||||
|
const st = String(status || 'PROCESSING').toUpperCase();
|
||||||
|
if (st === 'SUCCESS') return { ok: true, status: 'SUCCESS', refundId, outRefundNo };
|
||||||
|
if (st === 'PROCESSING') {
|
||||||
|
return { ok: false, pending: true, status: 'PROCESSING', refundId, outRefundNo, error: '微信退款处理中' };
|
||||||
|
}
|
||||||
|
return { ok: false, status: st, refundId, outRefundNo, error: `微信退款未成功:${st}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveWechatRefundStatus(cfg: any, outRefundNo: string, hinted?: string): Promise<string> {
|
||||||
|
let status = String(hinted || '').toUpperCase();
|
||||||
|
if (status === 'SUCCESS' || status === 'CLOSED' || status === 'ABNORMAL') return status;
|
||||||
|
for (let i = 0; i < 3; i += 1) {
|
||||||
|
if (i > 0) await new Promise((resolve) => setTimeout(resolve, 500));
|
||||||
|
try {
|
||||||
|
const queried = await queryRefundByOutRefundNo(cfg, outRefundNo);
|
||||||
|
status = String((queried && queried.status) || status || 'PROCESSING').toUpperCase();
|
||||||
|
if (status === 'SUCCESS' || status === 'CLOSED' || status === 'ABNORMAL') return status;
|
||||||
|
} catch (e) {
|
||||||
|
logServerError('wechatRefund.query', e);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return status || 'PROCESSING';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注册微信原路退款执行器。只有 SUCCESS 视为到账;PROCESSING 交给退款回调补记。
|
||||||
setWeChatRefundFn(async (orderId, refundCents, totalCents, reason, outRefundNo) => {
|
setWeChatRefundFn(async (orderId, refundCents, totalCents, reason, outRefundNo) => {
|
||||||
try {
|
try {
|
||||||
const cfg: any = await resolveWechatPayRuntimeConfig();
|
const cfg: any = await resolveWechatPayRuntimeConfig();
|
||||||
if (!(cfg.effectiveMode === 'LIVE' && cfg.isReadyForLive)) {
|
if (!(cfg.effectiveMode === 'LIVE' && cfg.isReadyForLive)) {
|
||||||
return { ok: false, skipped: true, error: '微信支付未就绪' };
|
return { ok: false, skipped: true, error: '微信支付未就绪' };
|
||||||
}
|
}
|
||||||
// 幂等:已成功的退款直接返回
|
|
||||||
const existing = await repo.getRefundByOutRefundNo(outRefundNo);
|
const existing = await repo.getRefundByOutRefundNo(outRefundNo);
|
||||||
if (existing && existing.status === 'SUCCESS') {
|
if (existing && String(existing.status).toUpperCase() === 'SUCCESS') {
|
||||||
return { ok: true, status: 'SUCCESS', refundId: existing.refund_id };
|
if (Number(existing.refund_cents) !== Math.round(Number(refundCents) || 0)) {
|
||||||
|
return { ok: false, error: '退款单号已占用且金额不一致' };
|
||||||
}
|
}
|
||||||
|
return { ok: true, status: 'SUCCESS', refundId: existing.refund_id, outRefundNo };
|
||||||
|
}
|
||||||
|
let activeNo = outRefundNo;
|
||||||
|
if (existing && ['CLOSED', 'ABNORMAL'].includes(String(existing.status).toUpperCase())) {
|
||||||
|
activeNo = `${outRefundNo}_R${Date.now().toString(36)}`.replace(/[^A-Za-z0-9_]/g, '').slice(0, 64);
|
||||||
|
}
|
||||||
|
const active = activeNo === outRefundNo ? existing : await repo.getRefundByOutRefundNo(activeNo);
|
||||||
|
const submitted = !!(active && String(active.refund_id || '').trim());
|
||||||
|
// 先写入退款记录,微信回调即使早于本次 HTTP 响应返回也能找到订单
|
||||||
|
if (!submitted) {
|
||||||
|
await repo.upsertRefundRecord({
|
||||||
|
outRefundNo: activeNo,
|
||||||
|
outTradeNo: orderId,
|
||||||
|
orderId,
|
||||||
|
refundId: '',
|
||||||
|
refundCents,
|
||||||
|
totalCents,
|
||||||
|
status: 'PROCESSING',
|
||||||
|
reason,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let hinted = submitted ? String(active.status || '') : '';
|
||||||
|
let refundId = submitted ? active.refund_id : '';
|
||||||
|
if (!submitted) {
|
||||||
const resp = await createRefund(cfg, {
|
const resp = await createRefund(cfg, {
|
||||||
outTradeNo: orderId,
|
outTradeNo: orderId,
|
||||||
outRefundNo,
|
outRefundNo: activeNo,
|
||||||
refundCents,
|
refundCents,
|
||||||
totalCents,
|
totalCents,
|
||||||
reason,
|
reason,
|
||||||
notifyUrl: cfg.refundNotifyUrl || undefined,
|
notifyUrl: cfg.refundNotifyUrl || undefined,
|
||||||
});
|
});
|
||||||
|
hinted = String((resp && resp.status) || 'PROCESSING');
|
||||||
|
refundId = resp && resp.refund_id;
|
||||||
|
}
|
||||||
|
const status = await resolveWechatRefundStatus(cfg, activeNo, hinted);
|
||||||
|
await repo.upsertRefundRecord({
|
||||||
|
outRefundNo: activeNo,
|
||||||
|
outTradeNo: orderId,
|
||||||
|
orderId,
|
||||||
|
refundId,
|
||||||
|
refundCents,
|
||||||
|
totalCents,
|
||||||
|
status,
|
||||||
|
reason,
|
||||||
|
});
|
||||||
|
return wechatRefundResult(status, activeNo, refundId);
|
||||||
|
} catch (e: any) {
|
||||||
|
logServerError('wechatRefund', e);
|
||||||
|
try {
|
||||||
|
const cfg: any = await resolveWechatPayRuntimeConfig();
|
||||||
|
const status = await resolveWechatRefundStatus(cfg, outRefundNo);
|
||||||
|
if (status === 'SUCCESS' || status === 'PROCESSING' || status === 'CLOSED' || status === 'ABNORMAL') {
|
||||||
await repo.upsertRefundRecord({
|
await repo.upsertRefundRecord({
|
||||||
outRefundNo,
|
outRefundNo,
|
||||||
outTradeNo: orderId,
|
outTradeNo: orderId,
|
||||||
orderId,
|
orderId,
|
||||||
refundId: resp && resp.refund_id,
|
|
||||||
refundCents,
|
refundCents,
|
||||||
totalCents,
|
totalCents,
|
||||||
status: String((resp && resp.status) || 'PROCESSING'),
|
status,
|
||||||
reason,
|
reason,
|
||||||
});
|
});
|
||||||
return { ok: true, status: String((resp && resp.status) || 'PROCESSING'), refundId: resp && resp.refund_id };
|
return wechatRefundResult(status, outRefundNo);
|
||||||
} catch (e: any) {
|
}
|
||||||
logServerError('wechatRefund', e);
|
} catch (queryErr) {
|
||||||
|
logServerError('wechatRefund.recover', queryErr);
|
||||||
|
}
|
||||||
return { ok: false, error: (e && e.message) || String(e) };
|
return { ok: false, error: (e && e.message) || String(e) };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -3635,6 +3701,10 @@ app.post('/api/pay/wechat/refund-notify', async (req: Request, res: Response) =>
|
|||||||
const refundStatus = plain && (plain.refund_status || plain.status);
|
const refundStatus = plain && (plain.refund_status || plain.status);
|
||||||
if (outRefundNo && refundStatus) {
|
if (outRefundNo && refundStatus) {
|
||||||
const existing = await repo.getRefundByOutRefundNo(String(outRefundNo));
|
const existing = await repo.getRefundByOutRefundNo(String(outRefundNo));
|
||||||
|
const normalized = String(refundStatus).toUpperCase();
|
||||||
|
if (normalized === 'SUCCESS') {
|
||||||
|
await repo.completeAcceptedWechatRefund(String(outRefundNo));
|
||||||
|
} else {
|
||||||
await repo.upsertRefundRecord({
|
await repo.upsertRefundRecord({
|
||||||
outRefundNo: String(outRefundNo),
|
outRefundNo: String(outRefundNo),
|
||||||
outTradeNo: String((plain && plain.out_trade_no) || (existing && existing.out_trade_no) || ''),
|
outTradeNo: String((plain && plain.out_trade_no) || (existing && existing.out_trade_no) || ''),
|
||||||
@@ -3642,11 +3712,12 @@ app.post('/api/pay/wechat/refund-notify', async (req: Request, res: Response) =>
|
|||||||
refundId: String((plain && plain.refund_id) || (existing && existing.refund_id) || ''),
|
refundId: String((plain && plain.refund_id) || (existing && existing.refund_id) || ''),
|
||||||
refundCents: Number((existing && existing.refund_cents) || 0),
|
refundCents: Number((existing && existing.refund_cents) || 0),
|
||||||
totalCents: Number((existing && existing.total_cents) || 0),
|
totalCents: Number((existing && existing.total_cents) || 0),
|
||||||
status: String(refundStatus),
|
status: normalized,
|
||||||
reason: String((existing && existing.reason) || ''),
|
reason: String((existing && existing.reason) || ''),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
res.json({ code: 'SUCCESS', message: '成功' });
|
res.json({ code: 'SUCCESS', message: '成功' });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
res.status(500).json({ code: 'FAIL', message: err.message });
|
res.status(500).json({ code: 'FAIL', message: err.message });
|
||||||
@@ -3709,6 +3780,9 @@ app.post('/api/orders/:id/complete', async (req: Request, res: Response) => {
|
|||||||
if (!role.isAdmin && !role.isBuyer && !role.isCompanion) {
|
if (!role.isAdmin && !role.isBuyer && !role.isCompanion) {
|
||||||
return res.status(403).json({ code: 40300, message: '仅交易双方或平台管理员可完成该订单' });
|
return res.status(403).json({ code: 40300, message: '仅交易双方或平台管理员可完成该订单' });
|
||||||
}
|
}
|
||||||
|
if (!role.isAdmin && !role.isBuyer) {
|
||||||
|
return res.status(403).json({ code: 40300, message: '确认验收仅买家本人或平台管理员可操作,大神请先申请完成服务' });
|
||||||
|
}
|
||||||
const order = await repo.updateOrderStatus(orderId, '已完成');
|
const order = await repo.updateOrderStatus(orderId, '已完成');
|
||||||
pushUserNotification(Number(own.buyerId || 0), 'ORDER_STATUS', '订单已完成', `订单 ${orderId} 已完成,感谢使用,欢迎评价。`, '/pages/order/list');
|
pushUserNotification(Number(own.buyerId || 0), 'ORDER_STATUS', '订单已完成', `订单 ${orderId} 已完成,感谢使用,欢迎评价。`, '/pages/order/list');
|
||||||
const companionIds: number[] = Array.isArray(own?.companionIds) ? own.companionIds : [];
|
const companionIds: number[] = Array.isArray(own?.companionIds) ? own.companionIds : [];
|
||||||
@@ -3764,12 +3838,11 @@ app.post('/api/orders/:id/refund', async (req: Request, res: Response) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 管理员后台直接退款 (全额退款 / 部分退款,原路原渠道退回)
|
// 管理员后台直接退款 (全额退款 / 部分退款,原路原渠道退回)
|
||||||
app.post('/api/orders/:id/admin-refund', async (req: Request, res: Response) => {
|
app.post('/api/orders/:id/admin-refund', requireAdmin, async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const orderId = String(req.params.id);
|
const orderId = String(req.params.id);
|
||||||
const { refundType, refundAmount, reason } = req.body || {};
|
const { refundType, refundAmount, reason } = req.body || {};
|
||||||
const headerRole = req.headers['x-user-role'];
|
if (!isVerifiedAdminRequest(req)) {
|
||||||
if (headerRole === 'user' || headerRole === 'expert' || headerRole === 'PLAYER' || headerRole === 'EXPERT') {
|
|
||||||
return res.status(403).json({ code: 40300, message: '权限不足:仅平台管理员可执行直接退款' });
|
return res.status(403).json({ code: 40300, message: '权限不足:仅平台管理员可执行直接退款' });
|
||||||
}
|
}
|
||||||
const type = refundType === 'partial' ? 'partial' : 'full';
|
const type = refundType === 'partial' ? 'partial' : 'full';
|
||||||
@@ -3885,13 +3958,11 @@ app.get('/api/arbitrations', async (_req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post('/api/arbitrations/:id/handle', async (req: Request, res: Response) => {
|
app.post('/api/arbitrations/:id/handle', requireAdmin, async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const arbId = String(req.params.id);
|
const arbId = String(req.params.id);
|
||||||
const { decision, refundAmount, operatorRole } = req.body; // 'refund_full' | 'refund_partial' | 'reject' | 'deduct_credit'
|
const { decision, refundAmount } = req.body || {}; // 'refund_full' | 'refund_partial' | 'reject' | 'deduct_credit'
|
||||||
const headerRole = req.headers['x-user-role'];
|
if (!isVerifiedAdminRequest(req)) {
|
||||||
const callerRole = operatorRole || headerRole || 'admin';
|
|
||||||
if (callerRole === 'user' || callerRole === 'expert' || callerRole === 'PLAYER' || callerRole === 'EXPERT') {
|
|
||||||
return res.status(403).json({ code: 40300, message: '权限不足:买家与大神不可越权执行管理员仲裁' });
|
return res.status(403).json({ code: 40300, message: '权限不足:买家与大神不可越权执行管理员仲裁' });
|
||||||
}
|
}
|
||||||
const result = await repo.handleArbitration(arbId, decision, refundAmount !== undefined ? Number(refundAmount) : undefined);
|
const result = await repo.handleArbitration(arbId, decision, refundAmount !== undefined ? Number(refundAmount) : undefined);
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
jest.mock('../src/db/mysql', () => ({ pool: { getConnection: jest.fn(), query: jest.fn() } }));
|
||||||
|
jest.mock('../src/core/pay/refund-bridge', () => ({ tryRefundToWeChat: jest.fn() }));
|
||||||
|
|
||||||
|
import { pool } from '../src/db/mysql';
|
||||||
|
import { tryRefundToWeChat } from '../src/core/pay/refund-bridge';
|
||||||
|
import { MysqlRepository } from '../src/db/repository';
|
||||||
|
|
||||||
|
describe('核销与退款回归', () => {
|
||||||
|
beforeEach(() => jest.resetAllMocks());
|
||||||
|
|
||||||
|
it('同码同时匹配授权活动和订单时拒绝核销', async () => {
|
||||||
|
const conn = {
|
||||||
|
beginTransaction: jest.fn(), commit: jest.fn(), rollback: jest.fn(), release: jest.fn(),
|
||||||
|
query: jest.fn().mockResolvedValueOnce([[{ id: 'ticket' }]]).mockResolvedValueOnce([[{ id: 'order' }]]),
|
||||||
|
};
|
||||||
|
(pool.getConnection as jest.Mock).mockResolvedValue(conn);
|
||||||
|
await expect(new MysqlRepository().universalVerifyCheckin('1234', 1)).rejects.toMatchObject({ status: 409 });
|
||||||
|
expect(conn.rollback).toHaveBeenCalled();
|
||||||
|
expect(conn.commit).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([true, false])('微信明确未提交时仅释放新建占额(新建:%s)', async (newlyCreated) => {
|
||||||
|
const repository: any = new MysqlRepository();
|
||||||
|
repository.orderPaidViaWechat = jest.fn().mockResolvedValue({ wechat: true, totalCents: 1000 });
|
||||||
|
const release = jest.fn();
|
||||||
|
repository.occupyRefundSlot = jest.fn().mockResolvedValue({ release, newlyCreated });
|
||||||
|
(tryRefundToWeChat as jest.Mock).mockResolvedValue({ ok: false, skipped: true, error: '未配置' });
|
||||||
|
await expect(repository.refundOrderPayment({}, { id: 'order', amount: 10 }, 1000, '', '', 'TEST')).rejects.toThrow('未配置');
|
||||||
|
expect(pool.query).toHaveBeenCalledTimes(newlyCreated ? 1 : 0);
|
||||||
|
expect(release).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { buildOutRefundNo, canReserveRefund, clawbackDelta, payoutClawbackKind } from '../src/core/finance/clawback';
|
||||||
|
|
||||||
|
describe('退款回冲计算', () => {
|
||||||
|
it('整单结算后按仍留在平台的金额扣回,两次退完扣满', () => {
|
||||||
|
const first = clawbackDelta(90, 0, 100, 0, 40);
|
||||||
|
expect(first).toBe(36);
|
||||||
|
const second = clawbackDelta(90, first, 100, 40, 60);
|
||||||
|
expect(second).toBe(54);
|
||||||
|
expect(first + second).toBe(90);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('剩余金额结算后再退,按剩余额扣满,不按原价打折', () => {
|
||||||
|
expect(clawbackDelta(54, 0, 100, 40, 60)).toBe(54);
|
||||||
|
expect(clawbackDelta(54, 0, 100, 40, 20)).toBe(18);
|
||||||
|
expect(clawbackDelta(54, 18, 100, 60, 40)).toBe(36);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('带比例后缀的分销流水也要回冲', () => {
|
||||||
|
expect(payoutClawbackKind('一级分销佣金 (5%)')).toBe('referral1');
|
||||||
|
expect(payoutClawbackKind('二级分销佣金 (2%)')).toBe('referral2');
|
||||||
|
expect(payoutClawbackKind('一级分销佣金')).toBe('referral1');
|
||||||
|
expect(payoutClawbackKind('大神完单收益结算')).toBe('expert');
|
||||||
|
expect(payoutClawbackKind('部分退款剩余结算')).toBe('expert');
|
||||||
|
expect(payoutClawbackKind('活动核销费用清算')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('处理中的退款占用可退额度', () => {
|
||||||
|
expect(canReserveRefund(10000, 0, 4000, 6000)).toBe(true);
|
||||||
|
expect(canReserveRefund(10000, 0, 4000, 6001)).toBe(false);
|
||||||
|
expect(canReserveRefund(10000, 6000, 4000, 1000)).toBe(false);
|
||||||
|
expect(canReserveRefund(10000, 0, 0, 10000)).toBe(true);
|
||||||
|
expect(canReserveRefund(10000, 0, 0, 0)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('不同退款进度使用不同微信退款单号,同一笔重试单号不变', () => {
|
||||||
|
const first = buildOutRefundNo('ADM_PRFND', 'ord_1', 0, 4000);
|
||||||
|
const retry = buildOutRefundNo('ADM_PRFND', 'ord_1', 0, 4000);
|
||||||
|
const next = buildOutRefundNo('ADM_PRFND', 'ord_1', 4000, 6000);
|
||||||
|
expect(first).toBe(retry);
|
||||||
|
expect(next).not.toBe(first);
|
||||||
|
expect(first).toMatch(/^[A-Za-z0-9_]{6,64}$/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 资金闭环闸门:结算入口、退款回冲、组局同事务、分销封顶、支付后状态。
|
||||||
|
*/
|
||||||
|
describe('资金闭环闸门', () => {
|
||||||
|
const root = path.resolve(__dirname, '../../');
|
||||||
|
const read = (rel: string) => fs.readFileSync(path.join(root, rel), 'utf-8');
|
||||||
|
const repo = read('server/src/db/repository.ts');
|
||||||
|
const index = read('server/src/index.ts');
|
||||||
|
const list = read('pwuniapp/pages/order/list.vue');
|
||||||
|
|
||||||
|
const sliceFn = (code: string, name: string, len = 12000) => {
|
||||||
|
const start = code.indexOf(name);
|
||||||
|
expect(start).toBeGreaterThan(-1);
|
||||||
|
return code.slice(start, start + len);
|
||||||
|
};
|
||||||
|
|
||||||
|
it('完单结算只从待确认入账,退款回冲已入账佣金', () => {
|
||||||
|
const settle = sliceFn(repo, 'async completeOrderWithSettlement(');
|
||||||
|
expect(settle).toContain("String(order.status) !== '待确认'");
|
||||||
|
expect(settle).toContain('请先由大神申请完成并进入待确认');
|
||||||
|
expect(repo).toContain('async clawbackOrderSettlements(');
|
||||||
|
expect(repo).toContain("type = '结算回冲'");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('退款按剩余可退,部分结算走平台抽成配置', () => {
|
||||||
|
const refund = sliceFn(repo, 'async adminRefundOrder(', 8000);
|
||||||
|
expect(refund).toContain('totalOrderAmt - alreadyRefunded');
|
||||||
|
expect(refund).toContain('loadPayoutSplit');
|
||||||
|
expect(refund).not.toContain('* 0.9');
|
||||||
|
const arb = sliceFn(repo, 'async handleArbitration(', 12000);
|
||||||
|
expect(arb).toContain('loadPayoutSplit');
|
||||||
|
expect(arb).toContain('clawbackOrderSettlements');
|
||||||
|
expect(arb).not.toContain('* 0.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('组局核销、退席、解散同事务,收入记佣金且不可重复退', () => {
|
||||||
|
const verify = sliceFn(repo, 'async verifyCheckin(');
|
||||||
|
expect(verify).toContain('beginTransaction');
|
||||||
|
expect(verify).toContain('this.settleActivityCheckinAndReferral(');
|
||||||
|
const settle = sliceFn(repo, 'async settleActivityCheckinAndReferral(');
|
||||||
|
expect(settle).toContain('UPDATE users SET commission');
|
||||||
|
expect(repo).toContain('活动已解散,无法报名');
|
||||||
|
expect(repo).toContain('活动已解散,不可重复退款');
|
||||||
|
expect(repo).toContain("'活动核销回冲'");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('分销从平台抽成列支,一二级比例之和不得超过抽成', () => {
|
||||||
|
expect(repo).toContain('splitFundedPayout');
|
||||||
|
expect(repo).toContain('分销从平台抽成中列支');
|
||||||
|
const cfg = sliceFn(repo, 'async updateFinanceConfig(');
|
||||||
|
expect(cfg).toContain('一级与二级分销比例之和不能超过平台抽成比例');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('支付成功按是否指定大神写入待接单或履约中,超时与未支付取消补齐券和流水', () => {
|
||||||
|
const pay = sliceFn(repo, 'async applyPaymentSuccess(');
|
||||||
|
expect(pay).toContain("THEN '待接单'");
|
||||||
|
expect(pay).toContain("THEN '履约中'");
|
||||||
|
const timeout = sliceFn(repo, 'async processOrderTimeouts(');
|
||||||
|
expect(timeout).toContain('reverseUnpaidWechatLedger');
|
||||||
|
expect(timeout).toContain("status = '履约中'");
|
||||||
|
expect(timeout).toContain('claimed_by IS NULL OR claimed_by = 0');
|
||||||
|
expect(index).toContain('repo.adminCancelOrder(orderId)');
|
||||||
|
const route = index.indexOf("app.post('/api/orders/:id/pay'");
|
||||||
|
const sandbox = index.slice(route, route + 4200);
|
||||||
|
expect(sandbox).toContain("const paidStatus = isMarketplace ? '待接单' : '履约中'");
|
||||||
|
expect(sandbox).toContain("const allowedSandboxStatuses = ['履约中', '待接单']");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('后台直接退款和仲裁只认管理员令牌', () => {
|
||||||
|
const refundRoute = index.indexOf("app.post('/api/orders/:id/admin-refund'");
|
||||||
|
const refundBlock = index.slice(refundRoute, refundRoute + 700);
|
||||||
|
expect(refundBlock).toContain('requireAdmin');
|
||||||
|
expect(refundBlock).toContain('isVerifiedAdminRequest(req)');
|
||||||
|
expect(refundBlock).not.toContain("req.headers['x-user-role']");
|
||||||
|
const arbRoute = index.indexOf("app.post('/api/arbitrations/:id/handle'");
|
||||||
|
const arbBlock = index.slice(arbRoute, arbRoute + 500);
|
||||||
|
expect(arbBlock).toContain('requireAdmin');
|
||||||
|
expect(arbBlock).toContain('isVerifiedAdminRequest(req)');
|
||||||
|
expect(arbBlock).not.toContain('operatorRole');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('通用核销锁定具体票据并校验操作人', () => {
|
||||||
|
const verify = sliceFn(repo, 'async universalVerifyCheckin(');
|
||||||
|
expect(verify).toContain('a.creator_id = ?');
|
||||||
|
expect(verify).toContain('WHERE p.id = ? AND p.verify_code = ?');
|
||||||
|
expect(verify).toContain('FOR UPDATE');
|
||||||
|
expect(verify).toContain('无权核销该门票(非活动发起人或承接大神)');
|
||||||
|
expect(verify).toContain('核销码对应多张未核销门票,无法确定目标');
|
||||||
|
expect(verify).toContain("status IN ('履约中', '服务中')");
|
||||||
|
expect(verify).not.toContain('ORDER BY (a.creator_id = ?) DESC, p.created_at DESC\n LIMIT 1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('已结算订单不会把退款状态改回已完成', () => {
|
||||||
|
const settle = sliceFn(repo, 'async completeOrderWithSettlement(');
|
||||||
|
expect(settle).toContain('已阻止覆盖退款状态');
|
||||||
|
const settledAt = settle.indexOf('if (alreadySettled)');
|
||||||
|
const nextGate = settle.indexOf("String(order.status) !== '待确认'", settledAt);
|
||||||
|
const branch = settle.slice(settledAt, nextGate);
|
||||||
|
expect(branch).toContain("AND status = '待确认'");
|
||||||
|
expect(branch).not.toContain('WHERE id = ?", [order.id]');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('退款记录先于微信请求落库,处理中占用可退额度', () => {
|
||||||
|
const fn = index.indexOf('setWeChatRefundFn(async');
|
||||||
|
const block = index.slice(fn, fn + 2800);
|
||||||
|
const saveAt = block.indexOf('先写入退款记录');
|
||||||
|
const createAt = block.indexOf('createRefund(');
|
||||||
|
expect(saveAt).toBeGreaterThan(-1);
|
||||||
|
expect(createAt).toBeGreaterThan(saveAt);
|
||||||
|
const pay = sliceFn(repo, 'private async occupyRefundSlot(');
|
||||||
|
expect(pay).toContain('GET_LOCK');
|
||||||
|
expect(pay).toContain('canReserveRefund');
|
||||||
|
expect(pay).toContain('已有退款正在处理或超出可退金额');
|
||||||
|
const done = sliceFn(repo, 'async completeAcceptedWechatRefund(');
|
||||||
|
expect(done).toContain('退款记录尚未落库,拒绝确认该回调');
|
||||||
|
expect(done).toContain('部分退款剩余结算');
|
||||||
|
const settle = sliceFn(repo, 'async completeOrderWithSettlement(');
|
||||||
|
expect(settle).toContain('退款处理中,暂不可结算');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('微信退款只有 SUCCESS 才结案,PROCESSING 等回调补记', () => {
|
||||||
|
expect(index).toContain('pending: true');
|
||||||
|
expect(index).toContain('completeAcceptedWechatRefund');
|
||||||
|
const pay = sliceFn(repo, 'private async refundOrderPayment(');
|
||||||
|
expect(pay).toContain("wxStatus === 'SUCCESS'");
|
||||||
|
expect(pay).toContain('r.pending');
|
||||||
|
expect(pay).toContain('到账确认前不会把订单标成已退款');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('小程序确认验收只在待确认出现,列表支付不再自带履约中', () => {
|
||||||
|
expect(list).toContain("order.rawStatus === '待确认'");
|
||||||
|
const payStart = list.indexOf('const payOrder = async');
|
||||||
|
const pay = list.slice(payStart, payStart + 1400);
|
||||||
|
expect(pay).not.toContain("targetStatus: '履约中'");
|
||||||
|
expect(index).toContain('确认验收仅买家本人或平台管理员可操作,大神请先申请完成服务');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -57,11 +57,9 @@ describe('第七批安全加固闸门 (评价回复 / 服务上下架 / 通用
|
|||||||
describe('3. 通用核销归属 (生产闸门)', () => {
|
describe('3. 通用核销归属 (生产闸门)', () => {
|
||||||
it('生产环境必须校验核销人:活动=发起人,订单=承接大神', () => {
|
it('生产环境必须校验核销人:活动=发起人,订单=承接大神', () => {
|
||||||
const block = routeBlock("app.post('/api/verify/universal'");
|
const block = routeBlock("app.post('/api/verify/universal'");
|
||||||
expect(block).toContain('SECURE_MODE && !isVerifiedAdminRequest(req)');
|
expect(block).toContain('resolveSecureUserId');
|
||||||
expect(block).toContain("info.type === 'ACTIVITY'");
|
expect(block).toContain('repo.universalVerifyCheckin(String(verifyCode), operator, isVerifiedAdminRequest(req))');
|
||||||
expect(block).toContain('Number(info.creatorId) === operator');
|
expect(block).not.toContain('repo.queryCheckinCodeInfo');
|
||||||
expect(block).toContain('own!.companionIds.includes(operator)');
|
|
||||||
expect(block).toContain('无权核销该门票');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
在新工单中引用
屏蔽一个用户