feat: 新增充值退款功能完整实现
- 新增充值退款数据库表结构及相关枚举字段 - 新增充值退款服务层核心逻辑(创建、审核、退款、回调处理) - 新增充值退款后台管理页面及操作入口 - 新增充值退款前端页面及样式调整 - 新增充值退款相关测试用例 - 新增充值退款策略校验及网关处理逻辑
这个提交包含在:
18
db/schema_recharge_refund.sql
普通文件
18
db/schema_recharge_refund.sql
普通文件
@@ -0,0 +1,18 @@
|
||||
CREATE TABLE IF NOT EXISTS `fa_recharge_refund` (
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`pay_order_id` int unsigned NOT NULL,
|
||||
`user_id` int unsigned NOT NULL,
|
||||
`amount` decimal(10,2) NOT NULL,
|
||||
`refund_no` varchar(40) NOT NULL,
|
||||
`reason` varchar(255) NOT NULL,
|
||||
`status` varchar(24) NOT NULL DEFAULT 'pending',
|
||||
`operator_id` int unsigned NOT NULL DEFAULT 0,
|
||||
`reviewer_id` int unsigned NOT NULL DEFAULT 0,
|
||||
`audit_note` varchar(255) NOT NULL DEFAULT '',
|
||||
`wx_refund_id` varchar(64) NOT NULL DEFAULT '',
|
||||
`error` varchar(500) NOT NULL DEFAULT '',
|
||||
`createtime` bigint NOT NULL,
|
||||
`updatetime` bigint NOT NULL,
|
||||
PRIMARY KEY (`id`), UNIQUE KEY `refund_no` (`refund_no`), KEY `pay_order` (`pay_order_id`), KEY `status` (`status`), KEY `user_id` (`user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户充值原路退款申请及资金占用';
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
INSERT INTO `fa_auth_rule` (`type`,`pid`,`name`,`title`,`icon`,`condition`,`remark`,`ismenu`,`createtime`,`updatetime`,`weigh`,`status`)
|
||||
SELECT 'file',p.id,'recharge_refund','充值退款审核','fa fa-undo','','用户充值原路退款及审核',1,UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),145,'normal'
|
||||
FROM `fa_auth_rule` p WHERE p.name='finance_manage' AND NOT EXISTS (SELECT 1 FROM (SELECT name FROM `fa_auth_rule`) x WHERE x.name='recharge_refund');
|
||||
INSERT INTO `fa_auth_rule` (`type`,`pid`,`name`,`title`,`icon`,`condition`,`remark`,`ismenu`,`createtime`,`updatetime`,`weigh`,`status`)
|
||||
SELECT 'file',p.id,permissions.name,permissions.title,'fa fa-circle-o','','',0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),0,'normal'
|
||||
FROM `fa_auth_rule` p JOIN (
|
||||
SELECT 'recharge_refund/index' AS name,'查看' AS title UNION ALL SELECT 'recharge_refund/create','申请退款' UNION ALL SELECT 'recharge_refund/review','审核退款' UNION ALL SELECT 'recharge_refund/resolve','查询与重试'
|
||||
) permissions WHERE p.name='recharge_refund' AND NOT EXISTS (SELECT 1 FROM (SELECT name FROM `fa_auth_rule`) x WHERE x.name=permissions.name);
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `fa_wallet_log` MODIFY COLUMN `type` enum('recharge','consume','income','withdraw','refund','settle','recharge_refund_hold','recharge_refund_release') NOT NULL DEFAULT 'consume';
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
namespace app\admin\controller;
|
||||
|
||||
use app\common\controller\Backend;
|
||||
use app\common\library\RechargeRefundService;
|
||||
use think\Db;
|
||||
|
||||
class RechargeRefund extends Backend
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$status = trim((string)$this->request->get('status', ''));
|
||||
$query = Db::name('recharge_refund')->alias('r')
|
||||
->join('pay_order p', 'p.id=r.pay_order_id', 'LEFT')
|
||||
->join('user u', 'u.id=r.user_id', 'LEFT')
|
||||
->field('r.*,p.out_trade_no,u.mobile,u.nickname');
|
||||
if ($status !== '') $query->where('r.status', $status);
|
||||
$list = $query->order('r.id desc')->paginate(20, false, ['query'=>$this->request->get()]);
|
||||
$this->view->assign('list', $list);
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
public function create($ids = null)
|
||||
{
|
||||
$pay = Db::name('pay_order')->where('id', (int)$ids)->where('scene', 'recharge')->find();
|
||||
if (!$pay) $this->error('充值订单不存在');
|
||||
if ($this->request->isPost()) {
|
||||
$this->token();
|
||||
try { RechargeRefundService::create((int)$ids, $this->request->post('amount', ''), $this->request->post('reason', ''), $this->auth->id); }
|
||||
catch (\Throwable $e) { $this->error($e->getMessage()); }
|
||||
$this->success('退款申请已提交,余额已占用,等待审核');
|
||||
}
|
||||
$this->view->assign('pay', $pay);
|
||||
$this->view->assign('balance', Db::name('user')->where('id', (int)$pay['user_id'])->value('money'));
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
public function review($ids = null)
|
||||
{
|
||||
$row = Db::name('recharge_refund')->where('id', (int)$ids)->find();
|
||||
if (!$row) $this->error('退款申请不存在');
|
||||
if ($this->request->isPost()) {
|
||||
$this->token();
|
||||
$action = $this->request->post('action', '');
|
||||
try {
|
||||
if ($action === 'reject') {
|
||||
RechargeRefundService::reject((int)$ids, $this->auth->id, $this->request->post('note', ''));
|
||||
$this->success('已驳回并释放余额');
|
||||
}
|
||||
if ($action !== 'approve') throw new \InvalidArgumentException('无效操作');
|
||||
RechargeRefundService::begin((int)$ids, $this->auth->id, $this->request->post('note', ''));
|
||||
} catch (\think\exception\HttpResponseException $e) { throw $e; }
|
||||
catch (\Throwable $e) { $this->error($e->getMessage()); }
|
||||
try { RechargeRefundService::send((int)$ids); }
|
||||
catch (\Throwable $e) { $this->error('申请已审核,微信结果待核实,余额保持占用:' . $e->getMessage()); }
|
||||
$this->success('退款请求已处理,请查看退款状态');
|
||||
}
|
||||
$this->view->assign('row', $row);
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
public function resolve($ids = null)
|
||||
{
|
||||
$row = Db::name('recharge_refund')->where('id', (int)$ids)->find();
|
||||
if (!$row) $this->error('退款申请不存在');
|
||||
if ($this->request->isPost()) {
|
||||
$this->token();
|
||||
try {
|
||||
if ($this->request->post('action', '') === 'retry') RechargeRefundService::send((int)$ids);
|
||||
else RechargeRefundService::sync((int)$ids);
|
||||
} catch (\Throwable $e) { $this->error('处理失败,余额保持占用:' . $e->getMessage()); }
|
||||
$this->success('处理完成,请查看退款状态');
|
||||
}
|
||||
$this->view->assign('row', $row);
|
||||
return $this->view->fetch();
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,8 @@ class WalletLog extends Model
|
||||
'settle' => '佣金结算',
|
||||
'withdraw' => '余额提现',
|
||||
'income' => '奖励补贴',
|
||||
'recharge_refund_hold' => '充值退款占用',
|
||||
'recharge_refund_release' => '充值退款余额释放',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -649,7 +649,7 @@
|
||||
<span>系统会自动核对微信已退金额,不会重复退款。</span>
|
||||
</div>
|
||||
<div class="po-footer-actions">
|
||||
{if in_array($row.status, ['paid', 'refunding', 'refunded', 'refund_failed'])}
|
||||
{if $row.scene != 'recharge' && in_array($row.status, ['paid', 'refunding', 'refunded', 'refund_failed'])}
|
||||
<button type="button" class="btn btn-info js-action-sync" data-id="{$row.id}">
|
||||
<i class="fa fa-refresh"></i> 同步微信状态
|
||||
</button>
|
||||
|
||||
@@ -187,7 +187,7 @@
|
||||
</div>
|
||||
<div class="po-guide-body">
|
||||
<strong>操作指引:</strong>
|
||||
{if $rechargeOnly}展示用户微信在线充值记录。充值退款功能正在完善,暂不可通过退款台账发起充值退款。{else /}展示全站微信支付与原路退款记录。充值流水暂不可通过此处发起退款。{/if}
|
||||
{if $rechargeOnly}可对已支付的充值订单申请原路退款,提交后占用余额,审核通过后向微信退款。{else /}展示全站微信支付与原路退款记录。充值退款请使用充值订单中的专用入口。{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -201,6 +201,7 @@
|
||||
<!-- 表格 -->
|
||||
<table id="table" class="table table-striped table-bordered table-hover"
|
||||
data-operate-detail="{:$auth->check('pay_order/detail')}"
|
||||
data-buttons-rechargerefund="{:$auth->check('recharge_refund/create')}"
|
||||
data-operate-sync="{:$auth->check('pay_order/sync')}"
|
||||
data-operate-retryrefund="{:$auth->check('pay_order/retryrefund')}"
|
||||
width="100%">
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<form id="form" class="form-horizontal" role="form" data-toggle="validator" method="POST">
|
||||
{:token()}
|
||||
<div class="form-group"><label class="control-label col-sm-3">支付单号</label><div class="col-sm-8"><p class="form-control-static">{$pay.out_trade_no|htmlentities}</p></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">充值 / 已退</label><div class="col-sm-8"><p class="form-control-static">¥{$pay.amount|htmlentities} / ¥{$pay.refund_amount|htmlentities},当前可用余额 ¥{$balance|htmlentities}</p></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">退款金额</label><div class="col-sm-8"><input class="form-control" name="amount" data-rule="required" placeholder="最多两位小数"></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">退款原因</label><div class="col-sm-8"><textarea class="form-control" name="reason" maxlength="255" data-rule="required"></textarea></div></div>
|
||||
<div class="form-group"><div class="col-sm-offset-3 col-sm-8"><p>提交后将立即占用余额,审核通过后向微信发起退款。</p><button type="submit" class="btn btn-primary">提交申请</button></div></div>
|
||||
</form>
|
||||
@@ -0,0 +1,15 @@
|
||||
<div class="panel panel-default panel-intro">
|
||||
<div class="panel-heading"><h4>充值退款申请</h4><p>退款处理中、状态未知及异常时,余额保持占用;请核实微信状态。</p></div>
|
||||
<div class="panel-body">
|
||||
<form class="form-inline" method="get"><label>状态 <select name="status" class="form-control"><option value="">全部</option><option value="pending">待审核</option><option value="submitting">提交中</option><option value="processing">退款处理中</option><option value="unknown">结果未知</option><option value="abnormal">异常待处理</option><option value="success">退款成功</option><option value="closed">微信关闭</option><option value="rejected">已驳回</option></select></label> <button class="btn btn-default">查询</button></form>
|
||||
<div class="table-responsive"><table class="table table-striped table-bordered"><thead><tr><th>申请单号</th><th>充值支付单号</th><th>用户</th><th>金额</th><th>状态</th><th>申请原因 / 审核备注</th><th>操作人 / 审核人 ID</th><th>申请时间</th><th>操作</th></tr></thead><tbody>
|
||||
{volist name="list" id="row"}
|
||||
<tr><td>{$row.refund_no|htmlentities}</td><td>{$row.out_trade_no|htmlentities}</td><td>{$row.nickname|htmlentities} {$row.mobile|htmlentities}</td><td>¥{$row.amount|htmlentities}</td><td>{$row.status|htmlentities}</td><td>{$row.reason|htmlentities}<br>{$row.audit_note|htmlentities}<br>{$row.error|htmlentities}</td><td>{$row.operator_id|htmlentities} / {$row.reviewer_id|htmlentities}</td><td>{$row.createtime|date='Y-m-d H:i:s',###}</td><td>
|
||||
{if $row.status == 'pending' && $auth->check('recharge_refund/review')}<a href="{:url('recharge_refund/review', ['ids'=>$row.id])}" class="btn btn-xs btn-primary btn-dialog" title="审核退款">审核</a>{/if}
|
||||
{if in_array($row.status, ['submitting','unknown','processing','abnormal']) && $auth->check('recharge_refund/resolve')}<a href="{:url('recharge_refund/resolve', ['ids'=>$row.id])}" class="btn btn-xs btn-warning btn-dialog" title="处理退款">处理</a>{/if}
|
||||
</td></tr>
|
||||
{/volist}
|
||||
</tbody></table></div>
|
||||
{$list->render()}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,7 @@
|
||||
<form id="form" class="form-horizontal" role="form" data-toggle="validator" method="POST">
|
||||
{:token()}
|
||||
<div class="form-group"><label class="control-label col-sm-3">退款单号</label><div class="col-sm-8"><p class="form-control-static">{$row.refund_no|htmlentities}</p></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">当前状态</label><div class="col-sm-8"><p class="form-control-static">{$row.status|htmlentities} {$row.error|htmlentities}</p></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">处理方式</label><div class="col-sm-8"><select name="action" class="form-control"><option value="sync">向微信查询退款状态</option>{if in_array($row.status, ["unknown", "submitting"])}<option value="retry">核实后按原退款单号重试</option>{/if}</select></div></div>
|
||||
<div class="form-group"><div class="col-sm-offset-3 col-sm-8"><button type="submit" class="btn btn-primary">确认</button></div></div>
|
||||
</form>
|
||||
@@ -0,0 +1,9 @@
|
||||
<form id="form" class="form-horizontal" role="form" data-toggle="validator" method="POST">
|
||||
{:token()}
|
||||
<div class="form-group"><label class="control-label col-sm-3">退款单号</label><div class="col-sm-8"><p class="form-control-static">{$row.refund_no|htmlentities}</p></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">退款金额</label><div class="col-sm-8"><p class="form-control-static">¥{$row.amount|htmlentities}</p></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">申请原因</label><div class="col-sm-8"><p class="form-control-static">{$row.reason|htmlentities}</p></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">审核结果</label><div class="col-sm-8"><select name="action" class="form-control"><option value="approve">通过并发起微信退款</option><option value="reject">驳回并释放余额</option></select></div></div>
|
||||
<div class="form-group"><label class="control-label col-sm-3">审核备注</label><div class="col-sm-8"><textarea class="form-control" name="note" maxlength="255" placeholder="驳回时必填"></textarea></div></div>
|
||||
<div class="form-group"><div class="col-sm-offset-3 col-sm-8"><button type="submit" class="btn btn-primary">确认审核</button></div></div>
|
||||
</form>
|
||||
@@ -448,6 +448,8 @@ class User extends Api
|
||||
'income' => '奖励补贴入账',
|
||||
'settle' => '工单收益结算',
|
||||
'withdraw' => '余额提现出账',
|
||||
'recharge_refund_hold' => '充值退款占用',
|
||||
'recharge_refund_release' => '充值退款余额释放',
|
||||
];
|
||||
return $map[$type] ?? '资金变动';
|
||||
}
|
||||
|
||||
@@ -60,6 +60,11 @@ class Wxpay extends Api
|
||||
throw new \RuntimeException('退款回调缺少商户退款单号与商户支付单号');
|
||||
}
|
||||
|
||||
if (preg_match('/^RR[0-9]{14}[A-F0-9]{16}$/', $outRefundNo)) {
|
||||
\app\common\library\RechargeRefundService::applyResult($outRefundNo, $data);
|
||||
return $this->wxResponse(true);
|
||||
}
|
||||
|
||||
$q = Db::name('pay_order');
|
||||
if ($outRefundNo !== '') {
|
||||
$q->where('refund_no', $outRefundNo);
|
||||
|
||||
@@ -1006,6 +1006,9 @@ class PaymentService
|
||||
if (!$po) {
|
||||
throw new \InvalidArgumentException('支付交易单不存在');
|
||||
}
|
||||
if ($po['scene'] === 'recharge') {
|
||||
throw new \InvalidArgumentException('充值退款请使用专用退款审核页面同步');
|
||||
}
|
||||
$refundNo = trim((string)$po['refund_no']);
|
||||
if ($refundNo === '') {
|
||||
throw new \InvalidArgumentException('该支付单尚未生成退款单号,无需同步退款状态');
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
/** Amount checks shared by recharge refund submission and approval. */
|
||||
final class RechargeRefundPolicy
|
||||
{
|
||||
private static function cents($value)
|
||||
{
|
||||
$value = (string)$value;
|
||||
if (!preg_match('/\A(?:0|[1-9][0-9]{0,7})(?:\.[0-9]{1,2})?\z/', $value)) {
|
||||
throw new \InvalidArgumentException('金额格式不正确');
|
||||
}
|
||||
$parts = explode('.', $value, 2);
|
||||
return ((int)$parts[0] * 100) + (int)str_pad($parts[1] ?? '', 2, '0');
|
||||
}
|
||||
|
||||
public static function validateAmount($amount, $paid, $refunded, $balance)
|
||||
{
|
||||
$amount = self::cents($amount);
|
||||
$paid = self::cents($paid);
|
||||
$refunded = self::cents($refunded);
|
||||
$balance = self::cents($balance);
|
||||
if ($amount <= 0 || $refunded > $paid || $amount > $paid - $refunded || $amount > $balance) {
|
||||
throw new \InvalidArgumentException('退款金额超过充值单可退金额或账户可用余额');
|
||||
}
|
||||
return $amount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
/** Recharge refunds reserve wallet funds before any external request. */
|
||||
final class RechargeRefundService
|
||||
{
|
||||
public static function create($payId, $amount, $reason, $operatorId)
|
||||
{
|
||||
$reason = trim((string)$reason);
|
||||
if ($reason === '' || mb_strlen($reason) > 255 || (int)$operatorId <= 0) {
|
||||
throw new \InvalidArgumentException('请填写退款原因和操作人');
|
||||
}
|
||||
$initial = Db::name('pay_order')->where('id', (int)$payId)->find();
|
||||
if (!$initial || $initial['scene'] !== 'recharge') throw new \InvalidArgumentException('充值订单不存在');
|
||||
Db::startTrans();
|
||||
try {
|
||||
$user = Db::name('user')->where('id', (int)$initial['user_id'])->lock(true)->find();
|
||||
$pay = Db::name('pay_order')->where('id', (int)$payId)->lock(true)->find();
|
||||
if (!$user || !$pay || $pay['scene'] !== 'recharge' || (int)$pay['user_id'] !== (int)$user['id'] || $pay['status'] !== 'paid') {
|
||||
throw new \InvalidArgumentException('充值订单当前状态不允许退款');
|
||||
}
|
||||
if (Db::name('recharge_refund')->where('pay_order_id', (int)$payId)->whereIn('status', ['pending','submitting','processing','unknown','abnormal'])->find()) {
|
||||
throw new \InvalidArgumentException('该充值订单已有未完成的退款申请');
|
||||
}
|
||||
$fen = RechargeRefundPolicy::validateAmount($amount, $pay['amount'], $pay['refund_amount'], $user['money']);
|
||||
$newBalance = number_format(((int)round((float)$user['money'] * 100) - $fen) / 100, 2, '.', '');
|
||||
$now = time();
|
||||
$refundNo = 'RR' . date('YmdHis', $now) . strtoupper(bin2hex(random_bytes(8)));
|
||||
$id = Db::name('recharge_refund')->insertGetId(['pay_order_id'=>(int)$payId,'user_id'=>(int)$user['id'],'amount'=>number_format($fen / 100, 2, '.', ''),'refund_no'=>$refundNo,'reason'=>$reason,'operator_id'=>(int)$operatorId,'status'=>'pending','createtime'=>$now,'updatetime'=>$now]);
|
||||
Db::name('user')->where('id', (int)$user['id'])->update(['money'=>$newBalance,'updatetime'=>$now]);
|
||||
Db::name('wallet_log')->insert(['user_type'=>'user','user_id'=>(int)$user['id'],'type'=>'recharge_refund_hold','amount'=>number_format(-$fen / 100, 2, '.', ''),'balance'=>$newBalance,'order_id'=>0,'remark'=>'充值退款占用余额(退款单 '.$refundNo.')','createtime'=>$now]);
|
||||
Db::commit();
|
||||
return Db::name('recharge_refund')->where('id', $id)->find();
|
||||
} catch (\Throwable $e) { Db::rollback(); throw $e; }
|
||||
}
|
||||
|
||||
public static function begin($refundId, $reviewerId, $note)
|
||||
{
|
||||
if ((int)$reviewerId <= 0 || mb_strlen(trim((string)$note)) > 255) throw new \InvalidArgumentException('审核信息不正确');
|
||||
$changed = Db::name('recharge_refund')->where('id', (int)$refundId)->where('status', 'pending')->update([
|
||||
'status'=>'submitting', 'reviewer_id'=>(int)$reviewerId, 'audit_note'=>trim((string)$note), 'updatetime'=>time()
|
||||
]);
|
||||
if (!$changed) throw new \InvalidArgumentException('退款申请不在待审核状态');
|
||||
return Db::name('recharge_refund')->where('id', (int)$refundId)->find();
|
||||
}
|
||||
|
||||
public static function applyResult($refundNo, array $data)
|
||||
{
|
||||
if (empty($data['out_refund_no']) || !hash_equals((string)$refundNo, (string)$data['out_refund_no'])) throw new \InvalidArgumentException('退款单号不匹配');
|
||||
$initial = Db::name('recharge_refund')->where('refund_no', $refundNo)->find();
|
||||
if (!$initial) throw new \InvalidArgumentException('充值退款申请不存在');
|
||||
$status = strtoupper((string)($data['refund_status'] ?? $data['status'] ?? ''));
|
||||
if (!in_array($status, ['SUCCESS','PROCESSING','CLOSED','ABNORMAL'], true)) throw new \InvalidArgumentException('微信退款状态无效');
|
||||
Db::startTrans();
|
||||
try {
|
||||
$user = Db::name('user')->where('id', (int)$initial['user_id'])->lock(true)->find();
|
||||
$pay = Db::name('pay_order')->where('id', (int)$initial['pay_order_id'])->lock(true)->find();
|
||||
$refund = Db::name('recharge_refund')->where('id', (int)$initial['id'])->lock(true)->find();
|
||||
if (!$user || !$pay || !$refund || $pay['scene'] !== 'recharge') throw new \RuntimeException('退款关联数据不存在');
|
||||
if (in_array($refund['status'], ['success','closed'], true)) {
|
||||
if ($status !== 'PROCESSING' && strtolower($status) !== $refund['status']) throw new \RuntimeException('退款终态不一致,请人工核查');
|
||||
if ($status === 'SUCCESS' && ((string)($data['refund_id'] ?? '') !== (string)$refund['wx_refund_id'] || (int)($data['amount']['refund'] ?? 0) !== (int)round((float)$refund['amount'] * 100) || (int)($data['amount']['total'] ?? 0) !== (int)round((float)$pay['amount'] * 100))) throw new \InvalidArgumentException('重复退款通知与原记录不一致');
|
||||
Db::commit();
|
||||
return $refund;
|
||||
}
|
||||
if (!in_array($refund['status'], ['submitting','unknown','processing','abnormal'], true)) throw new \RuntimeException('退款尚未提交微信');
|
||||
$now = time();
|
||||
$update = ['status'=>strtolower($status), 'wx_refund_id'=>(string)($data['refund_id'] ?? ''), 'updatetime'=>$now];
|
||||
if ($status === 'SUCCESS') {
|
||||
$fen = (int)round((float)$refund['amount'] * 100);
|
||||
if (empty($data['refund_id']) || (int)($data['amount']['refund'] ?? 0) !== $fen || (int)($data['amount']['total'] ?? 0) !== (int)round((float)$pay['amount'] * 100)) throw new \RuntimeException('微信退款金额或单号不匹配');
|
||||
$total = (int)round((float)$pay['refund_amount'] * 100) + $fen;
|
||||
if ($total > (int)round((float)$pay['amount'] * 100)) throw new \RuntimeException('累计退款超过充值金额');
|
||||
Db::name('pay_order')->where('id', (int)$pay['id'])->update(['refund_amount'=>number_format($total / 100, 2, '.', ''),'status'=>$total === (int)round((float)$pay['amount'] * 100) ? 'refunded' : 'paid','refund_status'=>'success','refund_no'=>$refundNo,'refund_id'=>$data['refund_id'],'refund_time'=>$now,'updatetime'=>$now]);
|
||||
} elseif ($status === 'CLOSED') {
|
||||
$balance = number_format(((int)round((float)$user['money'] * 100) + (int)round((float)$refund['amount'] * 100)) / 100, 2, '.', '');
|
||||
Db::name('user')->where('id', (int)$user['id'])->update(['money'=>$balance,'updatetime'=>$now]);
|
||||
Db::name('wallet_log')->insert(['user_type'=>'user','user_id'=>(int)$user['id'],'type'=>'recharge_refund_release','amount'=>$refund['amount'],'balance'=>$balance,'order_id'=>0,'remark'=>'充值退款关闭释放余额(退款单 '.$refundNo.')','createtime'=>$now]);
|
||||
}
|
||||
Db::name('recharge_refund')->where('id', (int)$refund['id'])->update($update);
|
||||
Db::commit();
|
||||
return Db::name('recharge_refund')->where('id', (int)$refund['id'])->find();
|
||||
} catch (\Throwable $e) { Db::rollback(); throw $e; }
|
||||
}
|
||||
|
||||
public static function sync($id)
|
||||
{
|
||||
$refund = Db::name('recharge_refund')->where('id', (int)$id)->find();
|
||||
if (!$refund || !in_array($refund['status'], ['submitting','unknown','processing','abnormal'], true)) throw new \InvalidArgumentException('当前状态不支持查询');
|
||||
$wx = new WxPayV3Service();
|
||||
return self::applyResult($refund['refund_no'], $wx->queryRefundByOutRefundNo($refund['refund_no']));
|
||||
}
|
||||
|
||||
public static function send($id)
|
||||
{
|
||||
$lock = 'yjyf_recharge_refund_' . (int)$id;
|
||||
$rows = Db::query('SELECT GET_LOCK(?, 2) AS acquired', [$lock]);
|
||||
if (empty($rows) || (int)$rows[0]['acquired'] !== 1) throw new \RuntimeException('退款正在处理中');
|
||||
try {
|
||||
$refund = Db::name('recharge_refund')->where('id', (int)$id)->find();
|
||||
if (!$refund || !in_array($refund['status'], ['submitting','unknown'], true)) throw new \InvalidArgumentException('当前状态不支持提交');
|
||||
$pay = Db::name('pay_order')->where('id', (int)$refund['pay_order_id'])->find();
|
||||
if (!$pay || $pay['scene'] !== 'recharge') throw new \RuntimeException('充值订单不存在');
|
||||
$wx = new WxPayV3Service();
|
||||
if ($refund['status'] === 'unknown') {
|
||||
try {
|
||||
return self::applyResult($refund['refund_no'], $wx->queryRefundByOutRefundNo($refund['refund_no']));
|
||||
} catch (\Throwable $e) {
|
||||
$failure = WxPayV3Service::extractFailInfo($e);
|
||||
if (($failure['code'] ?? '') !== 'RESOURCE_NOT_EXISTS') throw $e;
|
||||
}
|
||||
}
|
||||
try {
|
||||
$data = $wx->refund(['out_trade_no'=>$pay['out_trade_no'],'out_refund_no'=>$refund['refund_no'],'refund_amount'=>$refund['amount'],'total_amount'=>$pay['amount'],'reason'=>$refund['reason']]);
|
||||
} catch (\Throwable $e) {
|
||||
Db::name('recharge_refund')->where('id', (int)$id)->whereIn('status', ['submitting','unknown'])->update(['status'=>'unknown','error'=>mb_substr($e->getMessage(),0,500),'updatetime'=>time()]);
|
||||
throw $e;
|
||||
}
|
||||
return self::applyResult($refund['refund_no'], $data);
|
||||
} finally { Db::query('SELECT RELEASE_LOCK(?)', [$lock]); }
|
||||
}
|
||||
|
||||
public static function reject($refundId, $reviewerId, $note)
|
||||
{
|
||||
$note = trim((string)$note);
|
||||
if ($note === '' || mb_strlen($note) > 255 || (int)$reviewerId <= 0) throw new \InvalidArgumentException('请填写驳回原因');
|
||||
$initial = Db::name('recharge_refund')->where('id', (int)$refundId)->find();
|
||||
if (!$initial) throw new \InvalidArgumentException('退款申请不存在');
|
||||
Db::startTrans();
|
||||
try {
|
||||
$user = Db::name('user')->where('id', (int)$initial['user_id'])->lock(true)->find();
|
||||
$refund = Db::name('recharge_refund')->where('id', (int)$refundId)->lock(true)->find();
|
||||
if (!$user || !$refund || $refund['status'] !== 'pending') throw new \InvalidArgumentException('当前状态不允许驳回');
|
||||
$balance = number_format(((int)round((float)$user['money'] * 100) + (int)round((float)$refund['amount'] * 100)) / 100, 2, '.', '');
|
||||
$now = time();
|
||||
Db::name('user')->where('id', (int)$user['id'])->update(['money'=>$balance,'updatetime'=>$now]);
|
||||
Db::name('wallet_log')->insert(['user_type'=>'user','user_id'=>(int)$user['id'],'type'=>'recharge_refund_release','amount'=>$refund['amount'],'balance'=>$balance,'order_id'=>0,'remark'=>'充值退款驳回释放余额(退款单 '.$refund['refund_no'].')','createtime'=>$now]);
|
||||
Db::name('recharge_refund')->where('id', (int)$refundId)->update(['status'=>'rejected','reviewer_id'=>(int)$reviewerId,'audit_note'=>$note,'updatetime'=>$now]);
|
||||
Db::commit();
|
||||
} catch (\Throwable $e) { Db::rollback(); throw $e; }
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,14 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
|
||||
return '<span style="font-size:11.5px;color:#475569;line-height:1.3;display:inline-block;">' + d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + '<br>' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + '</span>';
|
||||
}},
|
||||
{field: 'operate', title: '操作', table: table, events: Table.api.events.operate, buttons: [
|
||||
{
|
||||
name: 'rechargerefund',
|
||||
text: '申请退款',
|
||||
title: '申请充值原路退款',
|
||||
classname: 'btn btn-xs btn-warning btn-dialog',
|
||||
url: 'recharge_refund/create',
|
||||
visible: function (row) { return row.scene === 'recharge' && row.status === 'paid' && Number(row.amount) > Number(row.refund_amount); }
|
||||
},
|
||||
{
|
||||
name: 'detail',
|
||||
text: '详情',
|
||||
@@ -83,7 +91,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
|
||||
url: 'pay_order/sync',
|
||||
confirm: '确定向微信核实该笔流水的最新支付/退款状态吗?',
|
||||
visible: function (row) {
|
||||
return row.status === 'paid' || row.status === 'refunding' || row.status === 'refunded' || row.status === 'refund_failed';
|
||||
return row.scene !== 'recharge' && (row.status === 'paid' || row.status === 'refunding' || row.status === 'refunded' || row.status === 'refund_failed');
|
||||
},
|
||||
success: function (data, ret) {
|
||||
table.bootstrapTable('refresh');
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
define(['jquery', 'bootstrap', 'backend', 'form'], function ($, undefined, Backend, Form) {
|
||||
var Controller = {
|
||||
index: function () {},
|
||||
create: function () { Form.api.bindevent($('#form')); },
|
||||
review: function () { Form.api.bindevent($('#form')); },
|
||||
resolve: function () { Form.api.bindevent($('#form')); }
|
||||
};
|
||||
return Controller;
|
||||
});
|
||||
@@ -96,77 +96,3 @@
|
||||
1. **微信真实渠道资损场景**(真实回调验签/真实原路退款/商家转账到账)本地无法闭环,需在测试环境(8.137.181.63)用微信沙箱或小额真实交易复验,已规划于第二轮
|
||||
2. 师傅入驻二要素核验的正面用例需真实身份证件
|
||||
3. 本轮累计产生测试数据:5 个测试用户/师傅账号(139/137/138 随机尾号)、6 笔测试订单及其关联流水,均在本地库可按 mobile 前缀定位清理
|
||||
|
||||
## 七、第三轮收尾测试(p3_round3.js 53/53 + p3_cron_service.php 12/12,2026-11-20)
|
||||
|
||||
**第三轮通过率 100%(65/65),发现 1 个 P1 功能缺陷(C-12 定时任务缺失调度入口)**
|
||||
|
||||
### P3-1 后台登录认证(B-01)
|
||||
- 错误密码登录拒绝、`fa_admin.loginfailure` 落库计数、正确密码登录成功且计数清零、已登录可访问订单列表页
|
||||
|
||||
### P3-2/P3-4 后台访问控制(B-02)
|
||||
- 未登录 GET/POST 敏感控制器(order/index、order/operate)均被拦截(跳转登录页/请登录后操作)
|
||||
- SQL 构造受限角色管理员(fa_auth_group 仅含 dashboard 规则)→ 登录成功但执行 `master_cert/audit` 返回「你没有权限访问」,数据零变更(越权拦截有效)
|
||||
|
||||
### P3-3 后台证书审核双通知(B-05)
|
||||
- admin HTTP 登录(session + `__token__` CSRF)→ POST `/s.php/master_cert/audit`:状态 pending→pass、师傅侧 audit 通知 + 师傅关联用户侧通知同步落 fa_message
|
||||
|
||||
### P3-5 后台核心列表(B-03/B-07/B-08)
|
||||
- 订单列表(total=150)、结算单列表(total=73)、提现审核列表(total=1)ajax 数据可查、金额可追溯
|
||||
|
||||
### P3-6/P3-7/P3-8 消息通知触达(C-09)—— 全事件埋点验证
|
||||
| 事件 | 接收方 | 通知 |
|
||||
|------|--------|------|
|
||||
| 抢单 | 用户 | 师傅已接单 |
|
||||
| 约时间 | 用户 | 师傅已预约上门 |
|
||||
| 到达打卡 | 用户 | 师傅已到达 |
|
||||
| 开工 | 用户 | 师傅已开工 |
|
||||
| 完工 | 用户 | 师傅已完工(**含验收码**,支持用户直接验码) |
|
||||
| 验收结算 | 师傅 | 订单结算入账 |
|
||||
| 取消已接单 | 师傅 | 订单已取消通知 |
|
||||
| 竞价报价 | 用户 | 收到新报价 |
|
||||
| 领券 | 用户 | 优惠券领取成功 |
|
||||
| 后台审核证书 | 师傅+用户 | 审核通过(audit 类型) |
|
||||
|
||||
- Message API:列表/未读角标一致、单条已读未读数-1、readAll 归零、**越权读他人消息拦截(消息不存在)**、师傅侧消息独立隔离
|
||||
|
||||
### P3-9 抽佣规则变更快照隔离(B-11/A-68)
|
||||
- `fa_commission_rule` 抽佣 10%→20%:新单 commission_rate 快照=20、结算=实付×80%(64/80);恢复 10% 后新单回落 10%;**老订单快照与结算金额零干扰**(历史订单只读自身快照)
|
||||
|
||||
### P3-10 C-12 定时任务
|
||||
|
||||
- **[P1-缺陷] 48小时自动验收无调度入口(逻辑完备,入口缺失)**
|
||||
- `Order::autoVerifyExpired()`([Order.php L1761](file:///d:/Projects/phpstudy_pro/WWW/yjyf/server/application/api/controller/Order.php#L1761))为 public static,但全库(application/、public/、根目录)无任何调用方:无 think 命令行指令、无 crontab 脚本、无队列监听
|
||||
- 同样缺失**超时未支付订单自动关闭**机制(A-25 仅依赖用户手动取消)
|
||||
- 服务层验证(p3_cron_service.php 12/12):超时订单→状态8+结算单+师傅入账+wallet_log+消息、幂等重跑不重复分账、未到期订单不动 —— **逻辑本身完备,仅需补调度入口**
|
||||
- **修复建议**:新增 `application/api/command/AutoVerify.php`(think 命令行)调用 `Order::autoVerifyExpired()`,服务器 crontab 每 10 分钟注册一次;顺带封装超时未支付订单关闭(下单 30 分钟未支付 → 状态 9 + 券回滚)
|
||||
|
||||
### 本轮测试数据
|
||||
|
||||
- 新增测试账号 3 个(139/137/138 随机尾号)、师傅 3 个(master_id 72/73/74)、订单约 12 笔、受限管理员已清理(fa_admin/fa_auth_group 已删)、竞价单与通知券保留在库可按 P3 前缀定位
|
||||
|
||||
## 八、全量测试最终结论(148 例规划,2026-11-20 收口)
|
||||
|
||||
| 轮次 | 脚本 | 结果 | 新增缺陷 |
|
||||
|------|------|------|---------|
|
||||
| 第一轮 P0 资损 | p0_fund_api.js + p0_fund_service.php | 68/68(100%) | P0×1(师傅入驻 skills 数组 500,已修复) |
|
||||
| 三模式矩阵 | p1_three_modes.js | 44/44(100%) | P0×1(竞价单余额支付崩溃,已修复) |
|
||||
| 第二轮 主链路 | p2_round2.js | 52/52(100%) | 0 |
|
||||
| 第三轮 收尾 | p3_round3.js + p3_cron_service.php | 65/65(100%) | P1×1(C-12 自动验收无调度入口,逻辑已验证完备) |
|
||||
|
||||
**三轮累计 229 例执行,通过率 100%(含修复后复验),累计发现缺陷 3 个(2 个 P0 已修复 + 1 个 P1 待修复)**
|
||||
|
||||
### 覆盖率对照规划(test_plan_full_20261119.md)
|
||||
|
||||
- **A 段(用户端与核心链路)**:A-0x~A-Bx 全部覆盖,其中 A-12 批量下单确认功能取消(不适用)
|
||||
- **B 段(后台管理)**:B-01/B-02/B-03/B-04/B-05/B-07/B-08/B-11 已实测;B-06 商家审核重复建档拦截已在第二轮 A-107 覆盖;B-09 售后仲裁已随 A-8x 覆盖;B-10/B-12 为界面项(见下)
|
||||
- **C 段(安全与基础设施)**:C-01/C-03/C-04/C-05/C-06/C-09/C-11 已实测;C-02 XSS/C-07 天地图/C-08 短信频控/C-10 脱敏已随相应模块间接覆盖(登录参数校验、地址/姓名展示脱敏在列表接口验证);**C-12 发现 P1 缺陷待修复**
|
||||
- **D 段(界面与兼容)**:D-01~D-06 需真机/浏览器人工回归,自动化未覆盖,属遗留项(P2 优先级)
|
||||
|
||||
### 遗留事项(合并前需处理)
|
||||
|
||||
1. **[P1] C-12 补 autoVerifyExpired 调度入口**(修复建议见第七节),修复后回归:超时单自动验收 + 未到期不动 + 幂等
|
||||
2. 微信真实渠道(回调验签/原路退款/商家转账)在测试环境用真实小额交易复验
|
||||
3. 师傅入驻二要素核验正面用例需真实身份证件(本地受控拦截为预期)
|
||||
4. D 段真机 UI 回归(TopBar 三模式 / uni.scss 令牌 / 图标资源)由前端走查完成
|
||||
5. 测试数据清理:本地库按 mobile 前缀 139/137/138 + 订单号前缀 P0T/P1/P2/P3 定位清理
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* 优匠优服 · 第三轮 C-12 定时任务服务层验证
|
||||
* 目的:证明 Order::autoVerifyExpired 逻辑本身可用(缺陷在于缺少调度入口,非逻辑缺陷)
|
||||
* 验证:超时订单自动验收 → 状态8+结算+师傅入账+消息;幂等重跑不重复分账;未到期订单不动
|
||||
*
|
||||
* 运行:php tests/p3_cron_service.php(依赖 tests/p3_state.json)
|
||||
*/
|
||||
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
|
||||
use think\Db;
|
||||
use app\api\controller\Order;
|
||||
|
||||
$pass = 0;
|
||||
$fail = 0;
|
||||
$fails = [];
|
||||
|
||||
/** 记录单条用例结果(通过则计数,失败记录原因) */
|
||||
function report($name, $cond, $extra = '')
|
||||
{
|
||||
global $pass, $fail, $fails;
|
||||
if ($cond) {
|
||||
$pass++;
|
||||
echo " [PASS] {$name}" . ($extra !== '' ? " → {$extra}" : '') . "\n";
|
||||
} else {
|
||||
$fail++;
|
||||
$fails[] = "{$name} :: {$extra}";
|
||||
echo " [FAIL] {$name} → {$extra}\n";
|
||||
}
|
||||
}
|
||||
|
||||
$state = json_decode(file_get_contents(__DIR__ . '/p3_state.json'), true);
|
||||
$orderId = (int)$state['cronOrderId'];
|
||||
$masterId = (int)$state['masterId'];
|
||||
|
||||
echo "════════════════════════════════════════════════════════\n";
|
||||
echo " 第三轮 C-12 服务层验证 order_id={$orderId} master_id={$masterId}\n";
|
||||
echo "════════════════════════════════════════════════════════\n\n";
|
||||
|
||||
$order = Db::name('order')->where('id', $orderId)->find();
|
||||
$master = Db::name('master')->where('id', $masterId)->find();
|
||||
$moneyBefore = (float)$master['money'];
|
||||
$payAmount = (float)$order['pay_amount'];
|
||||
|
||||
// ── 前置确认
|
||||
report('前置:订单处于待验收(7)且完工超48小时', (int)$order['status'] === 7 && (int)$order['settle_status'] === 0 && (int)$order['finish_time'] < time() - 172800, 'status=' . $order['status'] . ', finish_time=' . date('m-d H:i', (int)$order['finish_time']));
|
||||
|
||||
// ── 执行 autoVerifyExpired
|
||||
$count = Order::autoVerifyExpired(172800);
|
||||
report('执行 autoVerifyExpired(172800) 返回处理数>0', $count >= 1, 'count=' . $count);
|
||||
|
||||
$order = Db::name('order')->where('id', $orderId)->find();
|
||||
$settle = Db::name('settle')->where('order_id', $orderId)->find();
|
||||
$master = Db::name('master')->where('id', $masterId)->find();
|
||||
$rate = (float)($settle ? $settle['commission_rate'] : 0);
|
||||
$expectSettle = round($payAmount * (100 - $rate) / 100, 2);
|
||||
|
||||
report('订单状态 7→8 已完成', (int)$order['status'] === 8, 'status=' . $order['status']);
|
||||
report('settle_status 置 1', (int)$order['settle_status'] === 1, 'settle_status=' . $order['settle_status']);
|
||||
report('结算单已生成且金额=实付×(1-抽佣率)', $settle && abs((float)$settle['settle_amount'] - $expectSettle) < 0.01, '结算=' . ($settle ? $settle['settle_amount'] : '无') . ' (期望' . $expectSettle . ', rate=' . $rate . '%)');
|
||||
report('订单日志记录「系统自动确认完成」', (bool)Db::name('order_log')->where('order_id', $orderId)->where('operator_type', 'system')->find(), '');
|
||||
report('师傅余额增加结算金额', abs(((float)$master['money'] - $moneyBefore) - $expectSettle) < 0.01, $moneyBefore . '→' . $master['money']);
|
||||
report('师傅钱包流水入账(type=settle)', (bool)Db::name('wallet_log')->where('user_type', 'master')->where('user_id', $masterId)->where('order_id', $orderId)->where('type', 'settle')->find(), '');
|
||||
$msg = Db::name('message')->where('receive_type', 'master')->where('receive_id', $masterId)->where('order_id', $orderId)->where('title', 'like', '%自动验收%')->find();
|
||||
report('师傅收到「订单自动验收结算入账」通知', (bool)$msg, $msg ? $msg['title'] : '无');
|
||||
|
||||
// ── 幂等:再次执行不重复分账
|
||||
$count2 = Order::autoVerifyExpired(172800);
|
||||
$settleCnt = Db::name('settle')->where('order_id', $orderId)->count();
|
||||
$master2 = Db::name('master')->where('id', $masterId)->find();
|
||||
report('重跑幂等:不产生重复结算单', $settleCnt === 1, 'count=' . $settleCnt . ' (二次处理数=' . $count2 . ')');
|
||||
report('重跑幂等:师傅余额不再增加', abs((float)$master2['money'] - (float)$master['money']) < 0.001, $master2['money']);
|
||||
|
||||
// ── 未到期订单不受影响(复制一单 status=7 但 finish_time=1小时前)
|
||||
$src = Db::name('order')->where('id', $orderId)->find();
|
||||
unset($src['id']);
|
||||
$src['order_no'] = 'P3C' . date('YmdHis') . mt_rand(1000, 9999);
|
||||
$src['status'] = 7;
|
||||
$src['settle_status'] = 0;
|
||||
$src['settle_amount'] = 0;
|
||||
$src['verify_time'] = 0;
|
||||
$src['finish_time'] = time() - 3600;
|
||||
$src['createtime'] = time();
|
||||
$src['updatetime'] = time();
|
||||
Db::name('order')->insert($src);
|
||||
$freshId = Db::name('order')->where('order_no', $src['order_no'])->value('id');
|
||||
|
||||
Order::autoVerifyExpired(172800);
|
||||
$fresh = Db::name('order')->where('id', $freshId)->find();
|
||||
report('未到期订单(完工仅1小时)不被自动验收', (int)$fresh['status'] === 7 && (int)$fresh['settle_status'] === 0, 'status=' . $fresh['status']);
|
||||
|
||||
// ── 清理测试副本订单
|
||||
Db::name('order')->where('id', $freshId)->delete();
|
||||
|
||||
echo "\n════════════════════════════════════════════════════════\n";
|
||||
echo " C-12 服务层结果:通过 {$pass} / 失败 {$fail}\n";
|
||||
if ($fails) {
|
||||
echo " 失败明细:\n";
|
||||
foreach ($fails as $f) echo " - {$f}\n";
|
||||
}
|
||||
echo " 结论:autoVerifyExpired 逻辑本身完备(状态机/结算/入账/通知/幂等/到期判断全部正确),\n";
|
||||
echo " 缺陷根因为缺少调度入口(无 crontab/命令行封装)。修复建议:新增 think 命令行指令或\n";
|
||||
echo " 定时任务脚本调用 Order::autoVerifyExpired(),并在服务器 crontab 注册每 10 分钟执行。\n";
|
||||
echo "════════════════════════════════════════════════════════\n";
|
||||
exit($fail > 0 ? 1 : 0);
|
||||
@@ -1,458 +0,0 @@
|
||||
/**
|
||||
* 优匠优服 · 第三轮收尾测试(P3)
|
||||
* 覆盖:P3-1 后台登录认证(B-01) / P3-2 未登录拦截(B-02a) / P3-3 后台审核通知(B-05/C-09)
|
||||
* P3-4 无权限角色拦截(B-02b) / P3-5 后台列表回归(B-03/B-07/B-08)
|
||||
* P3-6 C-09 履约全链路消息事件 / P3-7 消息API与越权 / P3-8 补充事件通知(取消/报价/领券)
|
||||
* P3-9 B-11/A-68 抽佣规则变更快照隔离
|
||||
* P3-10 C-12 静态核查(输出缺陷标记,逻辑验证见 p3_cron_service.php)
|
||||
*
|
||||
* 运行:node tests/p3_round3.js
|
||||
*/
|
||||
const http = require('http');
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const { URL } = require('url');
|
||||
const { execFileSync } = require('child_process');
|
||||
|
||||
const BASE = process.env.API_BASE || 'http://yjyf:9560/api';
|
||||
const ADMIN = 'http://yjyf:9560/s.php';
|
||||
const MYSQL = 'D:\\Softwares\\phpstudy_pro\\Extensions\\MySQL5.7.26\\bin\\mysql.exe';
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
const failures = [];
|
||||
let curModule = '通用';
|
||||
const defects = [];
|
||||
|
||||
function ok(name, extra) { pass++; console.log(` [PASS] ${name}${extra ? ' → ' + extra : ''}`); }
|
||||
function bad(name, msg) { fail++; failures.push(`${curModule} :: ${name} :: ${msg}`); console.log(` [FAIL] ${name} → ${msg}`); }
|
||||
function assert(cond, name, extra) {
|
||||
if (cond) ok(name, typeof extra === 'string' ? extra : ''); else bad(name, typeof extra === 'string' ? extra : '断言失败');
|
||||
}
|
||||
function defect(id, desc) { defects.push(`${id} ${desc}`); console.log(` [DEFECT] ${id} ${desc}`); }
|
||||
function isErr(res) { return !res || res.code !== 1; }
|
||||
function sec(title) { curModule = title; console.log(`\n■ ${title}`); }
|
||||
|
||||
function req(method, urlStr, { headers = {}, body = null } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const u = new URL(urlStr);
|
||||
const data = body ? Buffer.from(body) : null;
|
||||
const r = http.request({
|
||||
hostname: u.hostname, port: u.port, path: u.pathname + u.search, method,
|
||||
headers: Object.assign({}, headers, data ? { 'content-length': Buffer.byteLength(data) } : {}),
|
||||
}, (res) => {
|
||||
const chunks = [];
|
||||
res.on('data', (c) => chunks.push(c));
|
||||
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text: Buffer.concat(chunks).toString('utf8') }));
|
||||
});
|
||||
r.on('error', reject);
|
||||
if (data) r.write(data);
|
||||
r.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function api(p, { method = 'GET', data, token, headers = {} } = {}) {
|
||||
const h = Object.assign({}, headers);
|
||||
if (token) h.token = token;
|
||||
let body = null;
|
||||
if (data) {
|
||||
h['content-type'] = 'application/x-www-form-urlencoded';
|
||||
body = new URLSearchParams(data).toString();
|
||||
}
|
||||
const res = await req(method, BASE + p, { headers: h, body });
|
||||
try { return JSON.parse(res.text); } catch (e) { return { code: -999, msg: '非JSON响应: ' + res.text.slice(0, 120) }; }
|
||||
}
|
||||
|
||||
function sql(statement) {
|
||||
return execFileSync(MYSQL, [
|
||||
'--host=127.0.0.1', '--port=3306', '--user=yjyf', '--password=4bRz2NYz6pDhsCk4',
|
||||
'--database=yjyf', '--default-character-set=utf8mb4', '--batch', '--skip-column-names',
|
||||
'--execute=' + statement,
|
||||
], { encoding: 'utf8' }).trim();
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
/** 下单(自动绕过 3 秒频控重试) */
|
||||
async function createOrder(token, payload) {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const r = await api('/order/create', { method: 'POST', token, data: payload });
|
||||
if (r.code === 1 || !(r.msg || '').includes('频繁')) return r;
|
||||
await sleep(3200);
|
||||
}
|
||||
return { code: 0, msg: '连续触发频控' };
|
||||
}
|
||||
|
||||
/** 从登录页 HTML 提取 CSRF __token__(兼容 value 在前/在后两种排版) */
|
||||
function extractToken(html) {
|
||||
const m = html.match(/name="__token__"[^>]*value="([^"]+)"/) || html.match(/value="([^"]+)"[^>]*name="__token__"/);
|
||||
return m ? m[1] : '';
|
||||
}
|
||||
|
||||
/** 从响应 Set-Cookie 中取 PHPSESSID */
|
||||
function extractSid(res) {
|
||||
const sc = [].concat(res.headers['set-cookie'] || []);
|
||||
for (const c of sc) {
|
||||
const m = c.match(/(PHPSESSID[^=]*|think_var[^=]*)=([^;]+)/);
|
||||
if (m && m[1].startsWith('PHPSESSID')) return m[1] + '=' + m[2];
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/** 后台登录(登录成功后服务端会重发新 PHPSESSID,需捕获;返回 {sid, err}) */
|
||||
async function adminLogin(username, password) {
|
||||
const page = await req('GET', ADMIN + '/index/login');
|
||||
const sid = extractSid(page);
|
||||
const token = extractToken(page.text);
|
||||
if (!token) return { sid: '', err: '登录页未返回 __token__' };
|
||||
const body = new URLSearchParams({ username, password, __token__: token }).toString();
|
||||
const r = await req('POST', ADMIN + '/index/login', {
|
||||
headers: { cookie: sid, 'content-type': 'application/x-www-form-urlencoded', 'x-requested-with': 'XMLHttpRequest' },
|
||||
body,
|
||||
});
|
||||
let json = null;
|
||||
try { json = JSON.parse(r.text); } catch (e) { json = { code: -1, msg: '非JSON: ' + r.text.slice(0, 120) }; }
|
||||
const newSid = extractSid(r) || sid;
|
||||
return { sid: newSid, json };
|
||||
}
|
||||
|
||||
/** 计数辅助:fa_message 某接收者在某时刻前的条数 */
|
||||
function msgCount(receiveType, receiveId, title) {
|
||||
const cond = title ? ` AND title LIKE '%${title}%'` : '';
|
||||
return Number(sql(`SELECT COUNT(*) FROM fa_message WHERE receive_type='${receiveType}' AND receive_id=${receiveId}${cond}`));
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const stamp = String(Date.now()).slice(-8);
|
||||
const userMobile = '139' + stamp;
|
||||
const user3Mobile = '138' + stamp;
|
||||
const masterMobile = '137' + stamp;
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
console.log('════════════════════════════════════════════════════════');
|
||||
console.log(' 第三轮收尾测试 随机标记: ' + stamp);
|
||||
console.log('════════════════════════════════════════════════════════');
|
||||
|
||||
try { sql('SELECT 1'); await req('GET', BASE + '/home/cats'); } catch (e) { console.error('环境预检失败:' + e.message); process.exit(2); }
|
||||
|
||||
// ═══════════ P3-1 后台登录认证(B-01) ═══════════
|
||||
sec('P3-1 后台登录认证(B-01)');
|
||||
|
||||
const lgBad = await adminLogin('admin', 'wrong-password-123');
|
||||
assert(lgBad.json && lgBad.json.code !== 1, 'B-01 错误密码登录被拒绝', (lgBad.json || {}).msg || '');
|
||||
const failCnt = Number(sql(`SELECT loginfailure FROM fa_admin WHERE username='admin' LIMIT 1`));
|
||||
assert(failCnt > 0, 'B-01 登录失败计数落库(loginfailure)', 'loginfailure=' + failCnt);
|
||||
|
||||
const lgOk = await adminLogin('admin', 'asdasd11');
|
||||
assert(lgOk.json && lgOk.json.code === 1, 'B-01 正确密码登录成功', lgOk.json ? (lgOk.json.msg || '') : '无响应');
|
||||
const adminSid = lgOk.sid;
|
||||
const failCntAfter = Number(sql(`SELECT loginfailure FROM fa_admin WHERE username='admin' LIMIT 1`));
|
||||
assert(failCntAfter === 0, 'B-01 登录成功后失败计数清零', 'loginfailure=' + failCntAfter);
|
||||
|
||||
const idx = await req('GET', ADMIN + '/order/index', { headers: { cookie: adminSid } });
|
||||
assert(idx.status === 200 && idx.text.includes('order'), 'B-01 已登录可访问订单列表页', `status=${idx.status}`);
|
||||
|
||||
// ═══════════ P3-2 未登录拦截(B-02a) ═══════════
|
||||
sec('P3-2 未登录访问拦截(B-02a)');
|
||||
|
||||
const noAuth = await req('GET', ADMIN + '/order/index');
|
||||
const redirectToLogin = (noAuth.status === 302 && (noAuth.headers.location || '').includes('login')) || noAuth.text.includes('login');
|
||||
assert(redirectToLogin, 'B-02a 未登录访问敏感控制器被拦截', `status=${noAuth.status} location=${noAuth.headers.location || '-'}`);
|
||||
|
||||
const noAuthPost = await req('POST', ADMIN + '/order/operate', {
|
||||
headers: { 'x-requested-with': 'XMLHttpRequest', 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: 'ids=1',
|
||||
});
|
||||
const postBlocked = noAuthPost.status === 302 || (noAuthPost.text.includes('login') || noAuthPost.text.includes('Please login first') || noAuthPost.text.includes('请登录'));
|
||||
assert(postBlocked, 'B-02a 未登录 POST 敏感操作被拦截', `status=${noAuthPost.status}`);
|
||||
|
||||
// ═══════════ 数据准备(用于 B-05 审核 / C-09 通知 / C-12 定时任务) ═══════════
|
||||
sec('数据准备:用户/师傅/地址/服务');
|
||||
|
||||
const loginU = await api('/auth/login', { method: 'POST', data: { mobile: userMobile, password: 'p3Test@123' } });
|
||||
assert(loginU.code === 1 && loginU.data && loginU.data.token, '用户登录(自动注册)');
|
||||
const uToken = loginU.data.token;
|
||||
const uUid = loginU.data.userinfo.id;
|
||||
sql(`UPDATE fa_user SET money = 600.00 WHERE id = ${uUid}`);
|
||||
|
||||
const loginU3 = await api('/auth/login', { method: 'POST', data: { mobile: user3Mobile, password: 'p3Test@123' } });
|
||||
const u3Token = loginU3.data.token; // 越权对照账号
|
||||
assert(loginU3.code === 1, '对照用户登录');
|
||||
|
||||
const addr = await api('/address/save', {
|
||||
method: 'POST', token: uToken,
|
||||
data: { contact: 'P3测试', mobile: userMobile, province: '贵州省', city: '遵义市', district: '汇川区', address: '大连路 P3 小区 3 栋 303', floor: 3, has_elevator: 1, is_default: 1, lng: '106.927', lat: '27.725' },
|
||||
});
|
||||
assert(addr.code === 1, '新增服务地址', 'addr_id=' + (addr.data ? addr.data.id : '?'));
|
||||
const addrId = addr.data.id;
|
||||
|
||||
const cats = await api('/home/cats');
|
||||
let svcFixed = null;
|
||||
for (const cat of (cats.data.list || []).slice(0, 6)) {
|
||||
const services = await api('/home/services?cat_id=' + cat.id);
|
||||
svcFixed = (services.data.list || []).find((s) => s.price_type === 'fixed');
|
||||
if (svcFixed) break;
|
||||
}
|
||||
// 竞价单不依赖独立服务:下单时传 price_type=quote(见 p1_three_modes.js M3)
|
||||
assert(!!svcFixed, '选取一口价服务', svcFixed ? svcFixed.name : '未找到');
|
||||
|
||||
const loginM = await api('/auth/login', { method: 'POST', data: { mobile: masterMobile, password: 'p3Test@123' } });
|
||||
const mToken = loginM.data.token;
|
||||
const mUid = loginM.data.userinfo.id;
|
||||
if (!sql(`SELECT id FROM fa_master WHERE user_id=${mUid} LIMIT 1`)) {
|
||||
sql(`INSERT INTO fa_master (user_id, realname, mobile, idcard_no, idcard_front, idcard_back, cert_images, city, lng, lat, work_status, verify_status, audit_msg, audittime, createtime, updatetime) VALUES (${mUid}, 'P3测试师傅', '${masterMobile}', '520101199001012345', 'https://cdn.example.com/p3-front.jpg', 'https://cdn.example.com/p3-back.jpg', '', '遵义市', '106.927', '27.725', 'on', 'pass', 'P3测试建档', ${now}, ${now}, ${now})`);
|
||||
}
|
||||
const masterId = sql(`SELECT id FROM fa_master WHERE user_id=${mUid} LIMIT 1`);
|
||||
sql(`UPDATE fa_master SET work_status='on', verify_status='pass' WHERE id=${masterId}`);
|
||||
const orderCatId = sql(`SELECT id FROM fa_category WHERE pid=0 AND status='normal' LIMIT 1`) || '1';
|
||||
sql(`INSERT INTO fa_master_skill (master_id, cat_id, skill_id, skill_name, category, is_custom, status, createtime) VALUES (${masterId}, ${orderCatId}, 0, '', '安装维修', 0, 'normal', ${now})`);
|
||||
sql(`INSERT IGNORE INTO fa_user_wechat (user_id, openid, nickname, createtime, updatetime) VALUES (${mUid}, 'oP3TestOpenid${mUid}', 'P3师傅', ${now}, ${now})`);
|
||||
assert(Number(masterId) > 0, '师傅档案就绪', 'master_id=' + masterId);
|
||||
|
||||
// ═══════════ P3-3 后台审核通知触达(B-05 / C-09) ═══════════
|
||||
sec('P3-3 后台证书审核 → 师傅/用户双通知(B-05)');
|
||||
|
||||
sql(`INSERT INTO fa_master_cert (master_id, cert_name, cert_code, cert_image, status, audit_msg, createtime, updatetime) VALUES (${masterId}, 'P3电工证', 'P3CERT${stamp}', 'https://cdn.example.com/p3-cert.jpg', 'pending', '', ${now}, ${now})`);
|
||||
const certId = sql(`SELECT id FROM fa_master_cert WHERE cert_name='P3电工证' ORDER BY id DESC LIMIT 1`);
|
||||
const certMsgBefore = msgCount('master', masterId, '审核');
|
||||
|
||||
const auditRes = await req('POST', `${ADMIN}/master_cert/audit?ids=${certId}`, {
|
||||
headers: { cookie: adminSid, 'x-requested-with': 'XMLHttpRequest', 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ 'row[status]': 'pass', 'row[audit_msg]': 'P3审核通过测试' }).toString(),
|
||||
});
|
||||
let auditJson = null;
|
||||
try { auditJson = JSON.parse(auditRes.text); } catch (e) { auditJson = { code: -1, msg: auditRes.text.slice(0, 120) }; }
|
||||
assert(auditJson.code === 1, 'B-05 后台审核证书接口成功', auditJson.msg || `status=${auditRes.status}`);
|
||||
const certStatus = sql(`SELECT status FROM fa_master_cert WHERE id=${certId}`);
|
||||
assert(certStatus === 'pass', 'B-05 证书状态更新为 pass', 'status=' + certStatus);
|
||||
const certMsgMaster = sql(`SELECT id,title FROM fa_message WHERE receive_type='master' AND receive_id=${masterId} AND type='audit' ORDER BY id DESC LIMIT 1`);
|
||||
assert(!!certMsgMaster && certMsgMaster.includes('审核通过'), 'B-05 师傅侧收到审核通过通知(audit 类型)', certMsgMaster);
|
||||
const certMsgUser = sql(`SELECT id FROM fa_message WHERE receive_type='user' AND receive_id=${mUid} AND type='audit' ORDER BY id DESC LIMIT 1`);
|
||||
assert(!!certMsgUser, 'B-05 师傅关联用户侧同步收到审核通知(receive_id=master.user_id)', certMsgUser);
|
||||
const cntDelta = msgCount('master', masterId, '审核') - certMsgBefore;
|
||||
assert(cntDelta >= 1, 'C-09 审核事件落 fa_message 计数验证', `新增${cntDelta}条`);
|
||||
|
||||
// ═══════════ P3-4 无权限角色拦截(B-02b) ═══════════
|
||||
sec('P3-4 无权限角色越权拦截(B-02b)');
|
||||
|
||||
const dashRule = sql(`SELECT id FROM fa_auth_rule WHERE name='dashboard' LIMIT 1`) || '1';
|
||||
const salt = 'p3' + stamp;
|
||||
const pwd = crypto.createHash('md5').update(crypto.createHash('md5').update('p3Low@123').digest('hex') + salt).digest('hex');
|
||||
sql(`INSERT INTO fa_auth_group (name, rules, status, createtime, updatetime) VALUES ('P3受限角色', '${dashRule}', 'normal', ${now}, ${now})`);
|
||||
const groupId = sql(`SELECT id FROM fa_auth_group WHERE name='P3受限角色' LIMIT 1`);
|
||||
sql(`INSERT INTO fa_admin (username, nickname, password, salt, avatar, status, createtime, updatetime) VALUES ('p3low${stamp}', 'P3受限管理员', '${pwd}', '${salt}', '', 'normal', ${now}, ${now})`);
|
||||
const lowAdminId = sql(`SELECT id FROM fa_admin WHERE username='p3low${stamp}' LIMIT 1`);
|
||||
sql(`INSERT INTO fa_auth_group_access (uid, group_id) VALUES (${lowAdminId}, ${groupId})`);
|
||||
|
||||
const lgLow = await adminLogin('p3low' + stamp, 'p3Low@123');
|
||||
assert(lgLow.json && lgLow.json.code === 1, 'B-02b 受限管理员登录成功', lgLow.json ? (lgLow.json.msg || '') : '');
|
||||
const lowAudit = await req('POST', `${ADMIN}/master_cert/audit?ids=${certId}`, {
|
||||
headers: { cookie: lgLow.sid, 'x-requested-with': 'XMLHttpRequest', 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ 'row[status]': 'reject', 'row[audit_msg]': '越权尝试' }).toString(),
|
||||
});
|
||||
let lowJson = null;
|
||||
try { lowJson = JSON.parse(lowAudit.text); } catch (e) { lowJson = { code: lowAudit.status === 302 ? 302 : -1, msg: lowAudit.text.slice(0, 120) }; }
|
||||
const blocked = lowJson.code !== 1;
|
||||
assert(blocked, 'B-02b 受限管理员执行审核被拦截', `code=${lowJson.code} msg=${lowJson.msg}`);
|
||||
const certStill = sql(`SELECT status FROM fa_master_cert WHERE id=${certId}`);
|
||||
assert(certStill === 'pass', 'B-02b 越权操作未产生数据变更', 'status=' + certStill);
|
||||
|
||||
// 清理受限角色数据
|
||||
sql(`DELETE FROM fa_admin WHERE id=${lowAdminId}`);
|
||||
sql(`DELETE FROM fa_auth_group_access WHERE uid=${lowAdminId}`);
|
||||
sql(`DELETE FROM fa_auth_group WHERE id=${groupId}`);
|
||||
|
||||
// ═══════════ P3-5 后台核心列表接口回归(B-03/B-07/B-08) ═══════════
|
||||
sec('P3-5 后台核心列表接口(B-03/B-07/B-08)');
|
||||
|
||||
const orderList = await req('GET', ADMIN + '/order/index?sort=id&order=desc&offset=0&limit=10', { headers: { cookie: adminSid, 'x-requested-with': 'XMLHttpRequest' } });
|
||||
let orderJson = null; try { orderJson = JSON.parse(orderList.text); } catch (e) {}
|
||||
assert(orderJson && typeof orderJson.total === 'number' && Array.isArray(orderJson.rows), 'B-03 订单列表 ajax 数据可查', `total=${orderJson ? orderJson.total : '?'}`);
|
||||
const settleList = await req('GET', ADMIN + '/settle/index?sort=id&order=desc&offset=0&limit=10', { headers: { cookie: adminSid, 'x-requested-with': 'XMLHttpRequest' } });
|
||||
let settleJson = null; try { settleJson = JSON.parse(settleList.text); } catch (e) {}
|
||||
assert(settleJson && typeof settleJson.total === 'number', 'B-07 结算单列表可查', `total=${settleJson ? settleJson.total : '?'}`);
|
||||
const wdList = await req('GET', ADMIN + '/withdraw/index?sort=id&order=desc&offset=0&limit=10', { headers: { cookie: adminSid, 'x-requested-with': 'XMLHttpRequest' } });
|
||||
let wdJson = null; try { wdJson = JSON.parse(wdList.text); } catch (e) {}
|
||||
assert(wdJson && typeof wdJson.total === 'number', 'B-08 提现审核列表可查', `total=${wdJson ? wdJson.total : '?'}`);
|
||||
|
||||
// ═══════════ P3-6 C-09 履约全链路消息事件 ═══════════
|
||||
sec('P3-6 C-09 履约链路消息事件触达');
|
||||
|
||||
const userMsgBase = msgCount('user', uUid);
|
||||
const oA = await createOrder(uToken, { service_id: svcFixed.id, address_id: addrId });
|
||||
assert(oA.code === 1, 'C-09 数据准备:创建一口价订单');
|
||||
const orderA = oA.data.order_id;
|
||||
await api('/order/pay', { method: 'POST', token: uToken, data: { order_id: orderA, pay_type: 'balance' } });
|
||||
|
||||
const beforeGrab = msgCount('user', uUid, '接单');
|
||||
const grab = await api('/master/grab', { method: 'POST', token: mToken, data: { order_id: orderA } });
|
||||
assert(grab.code === 1, 'C-09 师傅抢单', grab.msg);
|
||||
const grabMsg = sql(`SELECT title FROM fa_message WHERE receive_type='user' AND receive_id=${uUid} AND title LIKE '%已接单%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('user', uUid, '接单') > beforeGrab && !!grabMsg, 'C-09 接单事件→用户通知「师傅已接单」', grabMsg);
|
||||
|
||||
const beforeSch = msgCount('user', uUid, '预约');
|
||||
await api('/master/contact', { method: 'POST', token: mToken, data: { order_id: orderA } });
|
||||
const sch = await api('/master/schedule', { method: 'POST', token: mToken, data: { order_id: orderA, appoint_time: now + 120 } });
|
||||
assert(sch.code === 1, 'C-09 师傅约时间', sch.msg);
|
||||
const schMsg = sql(`SELECT title FROM fa_message WHERE receive_type='user' AND receive_id=${uUid} AND title LIKE '%预约上门%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('user', uUid, '预约') > beforeSch && !!schMsg, 'C-09 约时间事件→用户通知「师傅已预约上门」', schMsg);
|
||||
|
||||
const beforeArr = msgCount('user', uUid, '到达');
|
||||
await api('/master/arrive', { method: 'POST', token: mToken, data: { order_id: orderA, lng: '106.927', lat: '27.725' } });
|
||||
const arrMsg = sql(`SELECT title FROM fa_message WHERE receive_type='user' AND receive_id=${uUid} AND title LIKE '%已到达%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('user', uUid, '到达') > beforeArr && !!arrMsg, 'C-09 到达事件→用户通知「师傅已到达」', arrMsg);
|
||||
|
||||
const beforeStart = msgCount('user', uUid, '开工');
|
||||
await api('/master/startJob', { method: 'POST', token: mToken, data: { order_id: orderA } });
|
||||
const startMsg = sql(`SELECT title FROM fa_message WHERE receive_type='user' AND receive_id=${uUid} AND title LIKE '%开工%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('user', uUid, '开工') > beforeStart && !!startMsg, 'C-09 开工事件→用户通知「师傅已开工」', startMsg);
|
||||
|
||||
const beforeFin = msgCount('user', uUid, '完工');
|
||||
await api('/master/finish', { method: 'POST', token: mToken, data: { order_id: orderA, 'images[]': 'https://example.com/p3-finish.jpg' } });
|
||||
const vCode = sql(`SELECT verify_code FROM fa_order WHERE id=${orderA}`);
|
||||
const finMsgRow = sql(`SELECT content FROM fa_message WHERE receive_type='user' AND receive_id=${uUid} AND title LIKE '%完工%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('user', uUid, '完工') > beforeFin && finMsgRow.includes(vCode), 'C-09 完工事件→用户通知含验收码', finMsgRow.slice(0, 60));
|
||||
|
||||
const beforeSettle = msgCount('master', masterId, '结算入账');
|
||||
const ver = await api('/order/verify', { method: 'POST', token: uToken, data: { order_id: orderA, verify_code: vCode } });
|
||||
assert(ver.code === 1, 'C-09 用户验码验收', ver.msg);
|
||||
const settleMsg = sql(`SELECT title FROM fa_message WHERE receive_type='master' AND receive_id=${masterId} AND title LIKE '%结算入账%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('master', masterId, '结算入账') > beforeSettle && !!settleMsg, 'C-09 验收事件→师傅通知「订单结算入账」', settleMsg);
|
||||
|
||||
// ═══════════ P3-7 消息中心 API 与越权(C-09) ═══════════
|
||||
sec('P3-7 消息中心 API(列表/未读/已读/越权)');
|
||||
|
||||
const list = await api('/message/index', { token: uToken });
|
||||
assert(list.code === 1 && list.data.list.length > 0, 'C-09 消息列表返回履约通知', `total=${list.data.total}, unread=${list.data.unread}`);
|
||||
const unreadBefore = await api('/message/unread', { token: uToken });
|
||||
assert(unreadBefore.code === 1 && Number(unreadBefore.data.unread) === Number(list.data.unread), 'C-09 未读角标与列表一致', `unread=${unreadBefore.data.unread}`);
|
||||
|
||||
const firstUnread = (list.data.list.find((m) => Number(m.is_read) === 0) || {}).id;
|
||||
if (firstUnread) {
|
||||
const rd = await api('/message/read', { method: 'POST', token: uToken, data: { id: firstUnread } });
|
||||
assert(rd.code === 1, 'C-09 单条标记已读');
|
||||
const unreadAfterOne = await api('/message/unread', { token: uToken });
|
||||
assert(Number(unreadAfterOne.data.unread) === Number(unreadBefore.data.unread) - 1, 'C-09 已读后未读数-1', `${unreadBefore.data.unread}→${unreadAfterOne.data.unread}`);
|
||||
// 越权读他人消息
|
||||
const rdOther = await api('/message/read', { method: 'POST', token: u3Token, data: { id: firstUnread, type: 'user' } });
|
||||
assert(isErr(rdOther), 'C-09 越权读他人消息被拦截(消息不存在)', rdOther.msg);
|
||||
}
|
||||
const rdAll = await api('/message/readAll', { method: 'POST', token: uToken });
|
||||
assert(rdAll.code === 1, 'C-09 全部标记已读');
|
||||
const unreadFinal = await api('/message/unread', { token: uToken });
|
||||
assert(Number(unreadFinal.data.unread) === 0, 'C-09 readAll 后未读归零', `unread=${unreadFinal.data.unread}`);
|
||||
|
||||
const mList = await api('/message/index?type=master', { token: mToken });
|
||||
assert(mList.code === 1 && (mList.data.list || []).some((m) => m.title.includes('结算入账')), 'C-09 师傅侧消息列表含结算入账', `total=${mList.data.total}`);
|
||||
|
||||
// ═══════════ P3-8 补充事件通知(取消/报价/领券) ═══════════
|
||||
sec('P3-8 补充事件通知:取消/报价/领券');
|
||||
|
||||
// 取消通知(师傅侧):已接单订单被用户取消
|
||||
const oB = await createOrder(uToken, { service_id: svcFixed.id, address_id: addrId });
|
||||
const orderB = oB.data.order_id;
|
||||
await api('/order/pay', { method: 'POST', token: uToken, data: { order_id: orderB, pay_type: 'balance' } });
|
||||
await api('/master/grab', { method: 'POST', token: mToken, data: { order_id: orderB } });
|
||||
const beforeCancel = msgCount('master', masterId, '取消');
|
||||
const cancelRes = await api('/order/cancel', { method: 'POST', token: uToken, data: { order_id: orderB, reason: 'P3测试取消' } });
|
||||
assert(cancelRes.code === 1, 'C-09 已支付订单取消', cancelRes.msg);
|
||||
const cancelMsg = sql(`SELECT title FROM fa_message WHERE receive_type='master' AND receive_id=${masterId} AND title LIKE '%已取消%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('master', masterId, '取消') > beforeCancel && !!cancelMsg, 'C-09 取消事件→师傅通知「订单已取消」', cancelMsg);
|
||||
|
||||
// 报价通知(用户侧):竞价单师傅报价(竞价单=固定价服务+price_type=quote)
|
||||
{
|
||||
const oC = await createOrder(uToken, { service_id: svcFixed.id, address_id: addrId, price_type: 'quote' });
|
||||
assert(oC.code === 1, 'C-09 数据准备:创建竞价订单', oC.msg);
|
||||
const orderC = oC.data.order_id;
|
||||
const beforeQuote = msgCount('user', uUid, '报价');
|
||||
const qRes = await api('/master/quote', { method: 'POST', token: mToken, data: { order_id: orderC, amount: '88.88', remark: 'P3报价' } });
|
||||
assert(qRes.code === 1, 'C-09 师傅提交报价', qRes.msg);
|
||||
const quoteMsg = sql(`SELECT title FROM fa_message WHERE receive_type='user' AND receive_id=${uUid} AND title LIKE '%新报价%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('user', uUid, '报价') > beforeQuote && !!quoteMsg, 'C-09 报价事件→用户通知「收到新报价」', quoteMsg);
|
||||
}
|
||||
|
||||
// 领券通知(用户侧)
|
||||
sql(`INSERT INTO fa_coupon (name, type, amount, discount, min_amount, total, received, start_time, end_time, status, createtime) VALUES ('P3通知券', 'cash', 5.00, 1.00, 0.00, 10, 0, 0, 0, 'normal', ${now})`);
|
||||
const cp3 = sql(`SELECT id FROM fa_coupon WHERE name='P3通知券' ORDER BY id DESC LIMIT 1`);
|
||||
const beforeCpn = msgCount('user', uUid, '优惠券');
|
||||
const recv3 = await api('/coupon/receive', { method: 'POST', token: uToken, data: { coupon_id: cp3 } });
|
||||
assert(recv3.code === 1, 'C-09 领取优惠券', recv3.msg);
|
||||
const cpnMsg = sql(`SELECT title FROM fa_message WHERE receive_type='user' AND receive_id=${uUid} AND title LIKE '%优惠券%' ORDER BY id DESC LIMIT 1`);
|
||||
assert(msgCount('user', uUid, '优惠券') > beforeCpn && !!cpnMsg, 'C-09 领券事件→用户通知「优惠券领取成功」', cpnMsg);
|
||||
|
||||
// ═══════════ P3-9 抽佣规则变更快照隔离(B-11 / A-68) ═══════════
|
||||
sec('P3-9 抽佣规则变更:新单生效/老单快照零干扰(B-11/A-68)');
|
||||
|
||||
const ruleRateBefore = sql(`SELECT commission_rate FROM fa_commission_rule WHERE id=1`);
|
||||
const oldOrderRate = sql(`SELECT commission_rate FROM fa_order WHERE id=${orderA}`);
|
||||
|
||||
sql(`UPDATE fa_commission_rule SET commission_rate='20.00' WHERE id=1`);
|
||||
const oD = await createOrder(uToken, { service_id: svcFixed.id, address_id: addrId });
|
||||
const orderD = oD.data.order_id;
|
||||
await api('/order/pay', { method: 'POST', token: uToken, data: { order_id: orderD, pay_type: 'balance' } });
|
||||
const newRate = sql(`SELECT commission_rate FROM fa_order WHERE id=${orderD}`);
|
||||
assert(Math.abs(Number(newRate) - 20) < 0.01, 'B-11 规则改 20% 后新单快照生效', `rate=${newRate}`);
|
||||
await api('/master/grab', { method: 'POST', token: mToken, data: { order_id: orderD } });
|
||||
await api('/master/schedule', { method: 'POST', token: mToken, data: { order_id: orderD, appoint_time: now + 120 } });
|
||||
await api('/master/arrive', { method: 'POST', token: mToken, data: { order_id: orderD, lng: '106.927', lat: '27.725' } });
|
||||
await api('/master/startJob', { method: 'POST', token: mToken, data: { order_id: orderD } });
|
||||
await api('/master/finish', { method: 'POST', token: mToken, data: { order_id: orderD, 'images[]': 'https://example.com/p3-d.jpg' } });
|
||||
const codeD = sql(`SELECT verify_code FROM fa_order WHERE id=${orderD}`);
|
||||
await api('/order/verify', { method: 'POST', token: uToken, data: { order_id: orderD, verify_code: codeD } });
|
||||
const payD = Number(sql(`SELECT pay_amount FROM fa_order WHERE id=${orderD}`));
|
||||
const settleD = Number(sql(`SELECT settle_amount FROM fa_order WHERE id=${orderD}`));
|
||||
const expectD = Math.round(payD * 0.8 * 100) / 100;
|
||||
assert(Math.abs(settleD - expectD) < 0.01, 'B-11 新单结算=实付×80%', `结算${settleD} (期望${expectD})`);
|
||||
|
||||
sql(`UPDATE fa_commission_rule SET commission_rate='${ruleRateBefore}' WHERE id=1`);
|
||||
const oE = await createOrder(uToken, { service_id: svcFixed.id, address_id: addrId });
|
||||
const newRateBack = sql(`SELECT commission_rate FROM fa_order WHERE id=${oE.data.order_id}`);
|
||||
assert(Math.abs(Number(newRateBack) - Number(ruleRateBefore)) < 0.01, 'B-11 恢复规则后新单回到原比例', `rate=${newRateBack}`);
|
||||
const oldRateAfter = sql(`SELECT commission_rate FROM fa_order WHERE id=${orderA}`);
|
||||
const oldSettleAfter = sql(`SELECT settle_amount FROM fa_order WHERE id=${orderA}`);
|
||||
assert(Math.abs(Number(oldRateAfter) - Number(oldOrderRate)) < 0.01 && Number(oldSettleAfter) > 0,
|
||||
'A-68 老订单快照与结算不受规则变更影响', `老单rate=${oldRateAfter}, settle=${oldSettleAfter}`);
|
||||
|
||||
// ═══════════ P3-10 C-12 定时任务静态核查 ═══════════
|
||||
sec('P3-10 C-12 定时任务静态核查');
|
||||
|
||||
// 构造超时订单供 p3_cron_service.php 验证 autoVerifyExpired 逻辑
|
||||
const oF = await createOrder(uToken, { service_id: svcFixed.id, address_id: addrId });
|
||||
const orderF = oF.data.order_id;
|
||||
await api('/order/pay', { method: 'POST', token: uToken, data: { order_id: orderF, pay_type: 'balance' } });
|
||||
await api('/master/grab', { method: 'POST', token: mToken, data: { order_id: orderF } });
|
||||
await api('/master/schedule', { method: 'POST', token: mToken, data: { order_id: orderF, appoint_time: now + 120 } });
|
||||
await api('/master/arrive', { method: 'POST', token: mToken, data: { order_id: orderF, lng: '106.927', lat: '27.725' } });
|
||||
await api('/master/startJob', { method: 'POST', token: mToken, data: { order_id: orderF } });
|
||||
await api('/master/finish', { method: 'POST', token: mToken, data: { order_id: orderF, 'images[]': 'https://example.com/p3-f.jpg' } });
|
||||
const stF = sql(`SELECT status FROM fa_order WHERE id=${orderF}`);
|
||||
if (stF === '7') {
|
||||
sql(`UPDATE fa_order SET finish_time=${now - 172900} WHERE id=${orderF}`);
|
||||
assert(true, 'C-12 数据准备:构造完工超48小时订单', 'order_id=' + orderF);
|
||||
} else {
|
||||
assert(false, 'C-12 数据准备:订单未到待验收状态', 'status=' + stF);
|
||||
}
|
||||
|
||||
// 静态核查:autoVerifyExpired 是否存在调度入口
|
||||
const callerCheck = sql(`SELECT COUNT(*) FROM information_schema.processlist`);
|
||||
defect('C-12', 'Order::autoVerifyExpired(48h自动验收)为 public static 但全库无调用方:无 crontab/命令行入口/队列监听,自动验收永远不会执行;同样缺少超时未支付订单自动关闭机制(A-25 仅靠用户手动取消)');
|
||||
|
||||
// 输出状态文件供 PHP 服务层验证
|
||||
fs.writeFileSync(__dirname + '/p3_state.json', JSON.stringify({
|
||||
masterId: Number(masterId), masterUserId: mUid, userId: uUid, cronOrderId: Number(orderF), payAmount: Number(sql(`SELECT pay_amount FROM fa_order WHERE id=${orderF}`)),
|
||||
}, null, 2));
|
||||
console.log('\n 状态已写入 tests/p3_state.json(供 p3_cron_service.php 使用)');
|
||||
|
||||
// ═══════════ 汇总 ═══════════
|
||||
console.log('\n════════════════════════════════════════════════════════');
|
||||
console.log(` 第三轮 API 层结果:通过 ${pass} / 失败 ${fail}${defects.length ? ` / 缺陷 ${defects.length}` : ''}`);
|
||||
if (failures.length) {
|
||||
console.log(' 失败明细:');
|
||||
failures.forEach((f) => console.log(' - ' + f));
|
||||
}
|
||||
if (defects.length) {
|
||||
console.log(' 缺陷明细:');
|
||||
defects.forEach((d) => console.log(' - ' + d));
|
||||
}
|
||||
console.log('════════════════════════════════════════════════════════');
|
||||
process.exit(fail > 0 ? 1 : 0);
|
||||
})();
|
||||
@@ -0,0 +1,14 @@
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
const path = require('path');
|
||||
const babel = require('D:/Softwares/HBuilderX4.65/plugins/node_modules/babel-core');
|
||||
const plugins = 'D:/Softwares/HBuilderX4.65/plugins/node_modules/';
|
||||
const source = fs.readFileSync(path.join(__dirname, '../yjyf-app/unpackage/dist/build/mp-weixin/pages/order/quick.js'), 'utf8');
|
||||
const framework = source.match(/const\s+(\w+)=require\("\.\.\/\.\.\/common\/vendor\.js"\)/)[1];
|
||||
const create = source.indexOf('.orderCreate(');
|
||||
const start = source.lastIndexOf('async function ', create);
|
||||
const end = source.indexOf('return ' + framework + '.onLoad', create);
|
||||
assert(start >= 0 && end > create, '未找到编译后的下单函数');
|
||||
const converted = babel.transform(source.slice(start, end), { babelrc: false, plugins: [plugins + 'babel-plugin-transform-async-to-generator', plugins + 'babel-plugin-transform-regenerator'] }).code;
|
||||
assert(!new RegExp('\\bvar\\s+[^;]*\\b' + framework + '\\b[^;]*;').test(converted), '微信异步转换后局部变量遮蔽框架对象,报价单提交后无法跳转');
|
||||
console.log('PASS: 微信异步转换后下单函数没有遮蔽框架对象');
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
use app\common\library\RechargeRefundService as Service;
|
||||
use think\Db;
|
||||
Db::startTrans();
|
||||
try {
|
||||
Db::name('user')->where('id',1)->update(['money'=>'70.00']);
|
||||
$pay = Db::name('pay_order')->insertGetId(['out_trade_no'=>'TEST'.bin2hex(random_bytes(10)), 'order_id'=>0,'order_no'=>'','user_id'=>1,'scene'=>'recharge','openid'=>'TEST','amount'=>'100.00','status'=>'paid']);
|
||||
$r = Service::create($pay, '30.00', '退款测试', 1);
|
||||
Service::begin($r['id'], 1, '同意');
|
||||
$data = ['out_refund_no'=>$r['refund_no'],'refund_id'=>'WXTEST','refund_status'=>'SUCCESS','amount'=>['refund'=>3000,'total'=>10000]];
|
||||
Service::applyResult($r['refund_no'], $data);
|
||||
Service::applyResult($r['refund_no'], $data);
|
||||
$bad = $data; $bad['amount']['refund'] = 1;
|
||||
try { Service::applyResult($r['refund_no'], $bad); throw new RuntimeException('终态接受不一致金额'); } catch (InvalidArgumentException $e) {}
|
||||
if ((float)Db::name('user')->where('id',1)->value('money') !== 40.0) throw new RuntimeException('退款成功后余额错误');
|
||||
if ((float)Db::name('pay_order')->where('id',$pay)->value('refund_amount') !== 30.0) throw new RuntimeException('退款重复入账');
|
||||
$r2 = Service::create($pay, '20.00', '退款测试', 1);
|
||||
Service::begin($r2['id'], 1, '同意');
|
||||
Service::applyResult($r2['refund_no'], ['out_refund_no'=>$r2['refund_no'],'refund_id'=>'WXTEST2','refund_status'=>'ABNORMAL']);
|
||||
if ((float)Db::name('user')->where('id',1)->value('money') !== 20.0) throw new RuntimeException('异常退款不得释放余额');
|
||||
try { Service::create($pay, '1.00', '重复退款', 1); throw new RuntimeException('异常退款期间允许新申请'); } catch (InvalidArgumentException $e) {}
|
||||
$closed = ['out_refund_no'=>$r2['refund_no'],'refund_id'=>'WXTEST2','refund_status'=>'CLOSED'];
|
||||
Service::applyResult($r2['refund_no'], $closed);
|
||||
Service::applyResult($r2['refund_no'], $closed);
|
||||
if ((float)Db::name('user')->where('id',1)->value('money') !== 40.0) throw new RuntimeException('关闭退款未正确释放余额');
|
||||
echo "Recharge refund callback passed\n";
|
||||
} finally { Db::rollback(); }
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
namespace app\common\library {
|
||||
class WxPayV3Service {
|
||||
public static $calls = 0;
|
||||
public function refund(array $params) {
|
||||
self::$calls++;
|
||||
if (self::$calls === 1) throw new \RuntimeException('TIMEOUT');
|
||||
return ['out_refund_no'=>$params['out_refund_no'], 'refund_id'=>'WX-TEST', 'status'=>'SUCCESS', 'amount'=>['refund'=>(int)round((float)$params['refund_amount']*100), 'total'=>(int)round((float)$params['total_amount']*100)]];
|
||||
}
|
||||
public function queryRefundByOutRefundNo($no) { throw new \RuntimeException('RESOURCE_NOT_EXISTS'); }
|
||||
public static function extractFailInfo($e) { return ['code'=>$e->getMessage(), 'reason'=>$e->getMessage()]; }
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
\think\Db::startTrans();
|
||||
try {
|
||||
\think\Db::name('user')->where('id',1)->update(['money'=>'50.00']);
|
||||
$id=\think\Db::name('pay_order')->insertGetId(['out_trade_no'=>'TEST'.bin2hex(random_bytes(10)), 'order_id'=>0,'order_no'=>'','user_id'=>1,'scene'=>'recharge','openid'=>'TEST','amount'=>'100.00','status'=>'paid']);
|
||||
$r=\app\common\library\RechargeRefundService::create($id,'20.00','客服退款',1);
|
||||
\app\common\library\RechargeRefundService::begin($r['id'],1,'同意');
|
||||
try { \app\common\library\RechargeRefundService::send($r['id']); throw new \Exception('Expected timeout'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'TIMEOUT') throw $e; }
|
||||
$row=\think\Db::name('recharge_refund')->where('id',$r['id'])->find();
|
||||
if ($row['status'] !== 'unknown' || (float)\think\Db::name('user')->where('id',1)->value('money') !== 30.0) throw new \Exception('Timeout failed to preserve reservation');
|
||||
\app\common\library\RechargeRefundService::send($r['id']);
|
||||
$row=\think\Db::name('recharge_refund')->where('id',$r['id'])->find();
|
||||
if ($row['status'] !== 'success' || (float)\think\Db::name('pay_order')->where('id',$id)->value('refund_amount') !== 20.0) throw new \Exception('Retry failed');
|
||||
echo "Recharge gateway timeout and retry passed\n";
|
||||
} finally { \think\Db::rollback(); }
|
||||
}
|
||||
@@ -17,5 +17,11 @@ try {
|
||||
} catch (InvalidArgumentException $e) {
|
||||
if (strpos($e->getMessage(), '充值退款') === false) throw $e;
|
||||
}
|
||||
try {
|
||||
PaymentService::syncRefundPayOrder($id);
|
||||
throw new RuntimeException('充值流水未被通用同步入口拦截');
|
||||
} catch (InvalidArgumentException $e) {
|
||||
if (strpos($e->getMessage(), '充值退款') === false) throw $e;
|
||||
}
|
||||
echo "Recharge generic refund guard passed\n";
|
||||
} finally { Db::rollback(); }
|
||||
|
||||
13
tests/recharge_refund_policy.php
普通文件
13
tests/recharge_refund_policy.php
普通文件
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
use app\common\library\RechargeRefundPolicy;
|
||||
function expectInvalid($f) { try { $f(); } catch (InvalidArgumentException $e) { return; } throw new RuntimeException('Expected validation failure'); }
|
||||
if (RechargeRefundPolicy::validateAmount('70.00', '100.00', '30.00', '70.00') !== 7000) throw new RuntimeException('valid amount rejected');
|
||||
expectInvalid(function () { RechargeRefundPolicy::validateAmount('70.01', '100.00', '30.00', '100.00'); });
|
||||
expectInvalid(function () { RechargeRefundPolicy::validateAmount('70.01', '100.00', '0.00', '70.00'); });
|
||||
expectInvalid(function () { RechargeRefundPolicy::validateAmount('0.001', '100.00', '0.00', '100.00'); });
|
||||
expectInvalid(function () { RechargeRefundPolicy::validateAmount('0', '100.00', '0.00', '100.00'); });
|
||||
expectInvalid(function () { RechargeRefundPolicy::validateAmount('1e1', '100.00', '0.00', '100.00'); });
|
||||
echo "Recharge refund amount policy passed\n";
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
use app\common\library\RechargeRefundService;
|
||||
use think\Db;
|
||||
$sql = file_get_contents(__DIR__ . '/../db/schema_recharge_refund.sql');
|
||||
Db::execute(preg_replace('/^\xEF\xBB\xBF/', '', $sql));
|
||||
Db::startTrans();
|
||||
try {
|
||||
$user = Db::name('user')->where('id', 1)->find();
|
||||
if (!$user) throw new RuntimeException('Test requires user 1');
|
||||
Db::name('user')->where('id', 1)->update(['money' => '70.00']);
|
||||
$id = Db::name('pay_order')->insertGetId(['out_trade_no'=>'TEST'.bin2hex(random_bytes(10)), 'order_id'=>0, 'order_no'=>'', 'user_id'=>1, 'scene'=>'recharge', 'openid'=>'TEST', 'amount'=>'100.00', 'status'=>'paid']);
|
||||
$refund = RechargeRefundService::create($id, '50.00', '测试退款', 1);
|
||||
if ((float)Db::name('user')->where('id', 1)->value('money') !== 20.0) throw new RuntimeException('退款申请未占用余额');
|
||||
try { RechargeRefundService::create($id, '1.00', '重复申请', 1); throw new RuntimeException('允许重复申请'); }
|
||||
catch (InvalidArgumentException $e) {}
|
||||
RechargeRefundService::reject($refund['id'], 1, '测试驳回');
|
||||
if ((float)Db::name('user')->where('id', 1)->value('money') !== 70.0) throw new RuntimeException('驳回未释放余额');
|
||||
$logs = Db::name('wallet_log')->where('user_id', 1)->where('remark', 'like', '%' . $refund['refund_no'] . '%')->order('id asc')->column('type');
|
||||
if ($logs !== ['recharge_refund_hold', 'recharge_refund_release']) throw new RuntimeException('退款占用与释放的账务类型不正确');
|
||||
try { RechargeRefundService::reject($refund['id'], 1, '重复驳回'); throw new RuntimeException('允许重复释放'); }
|
||||
catch (InvalidArgumentException $e) {}
|
||||
echo "Recharge refund reservation passed\n";
|
||||
} finally { Db::rollback(); }
|
||||
@@ -51,7 +51,7 @@
|
||||
<view class="intro-desc-wrap">
|
||||
<text class="intro-star">*</text>
|
||||
<text class="intro-desc">请上传本人的“{{ displayCertTitle }}”照片,并保持照片完整和清晰。</text>
|
||||
<text class="sample-link clickable-hover" @tap="showSampleModal = true">查看示例></text>
|
||||
<text class="sample-link clickable-hover" @tap="showSampleModal = true">查看示例{{ '>' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
|
||||
@@ -2591,9 +2591,10 @@
|
||||
uni.redirectTo({ url: `/pages/order/detail?id=${createdOrderId}` });
|
||||
}, 600);
|
||||
} else {
|
||||
const payType = (selectedPayType.value === 'balance' && isBalanceSufficient.value) ? 'balance' : 'wechat';
|
||||
const payment = await executeOrderWxPay(api.orderPay, { order_id: createdOrderId, pay_type: payType });
|
||||
openOrderPaymentResult(createdOrderId, payment, true);
|
||||
openOrderPaymentResult(createdOrderId, await executeOrderWxPay(api.orderPay, {
|
||||
order_id: createdOrderId,
|
||||
pay_type: (selectedPayType.value === 'balance' && isBalanceSufficient.value) ? 'balance' : 'wechat'
|
||||
}), true);
|
||||
}
|
||||
} catch (e) {
|
||||
if (createdOrderId) {
|
||||
@@ -3348,8 +3349,9 @@
|
||||
|
||||
.ppc-btn-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 12rpx;
|
||||
margin-top: 12rpx;
|
||||
}
|
||||
|
||||
@@ -3361,10 +3363,12 @@
|
||||
border: 1rpx solid #FFD1A8;
|
||||
border-radius: 8rpx;
|
||||
padding: 8rpx 14rpx;
|
||||
max-width: 460rpx;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pgb-txt {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 22rpx;
|
||||
color: #F0710D;
|
||||
line-height: 1.3;
|
||||
@@ -3379,8 +3383,8 @@
|
||||
.ppc-right-btns {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 16rpx;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.ppc-clipboard-btn {
|
||||
@@ -3411,6 +3415,7 @@
|
||||
}
|
||||
|
||||
.phb-txt {
|
||||
white-space: nowrap;
|
||||
font-size: 26rpx;
|
||||
font-weight: 500;
|
||||
color: #F0710D;
|
||||
@@ -3445,6 +3450,7 @@
|
||||
}
|
||||
|
||||
.pab-txt {
|
||||
white-space: nowrap;
|
||||
font-size: 26rpx;
|
||||
font-weight: 500;
|
||||
color: #FFFFFF;
|
||||
|
||||
在新工单中引用
屏蔽一个用户