fix: 完善取消退款恢复与师傅端流程
这个提交包含在:
11
docs/cancel-refund-recovery.md
普通文件
11
docs/cancel-refund-recovery.md
普通文件
@@ -0,0 +1,11 @@
|
||||
# 取消订单退款恢复任务
|
||||
|
||||
订单取消后,退款申请可能因进程中断、网络故障或微信异步处理而未完成。部署后需在运行后端的服务器上每分钟执行一次:
|
||||
|
||||
```sh
|
||||
cd /path/to/yjyf/server && php think order:refund-retry
|
||||
```
|
||||
|
||||
任务会查询已取消订单中尚待确认的微信支付,并核对、重试未完成的退款流水。退款失败时先查询原退款单;只有微信明确表示原单不存在,才使用同一退款单号重新提交。异常信息写入应用日志和支付流水,财务仍可在退款台账中查询、同步或重试。
|
||||
|
||||
仅注册命令不会使其自动运行。应通过服务器已有的计划任务系统配置执行频率,并使用该部署实际的 PHP 路径和项目目录。
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
namespace app\admin\command;
|
||||
|
||||
use app\common\library\OrderStatus;
|
||||
use app\common\library\PaymentService;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
use think\Db;
|
||||
|
||||
/** 定期执行:php think order:refund-retry */
|
||||
class OrderRefundRetry extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this->setName('order:refund-retry')->setDescription('核对并重试已取消订单的原路退款');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $output)
|
||||
{
|
||||
// 支付通知晚到或丢失时,先向微信确认取消订单下的待支付流水。
|
||||
$pending = Db::name('pay_order')->alias('p')
|
||||
->join('order o', 'o.id = p.order_id')
|
||||
->where('o.status', OrderStatus::CANCELLED)
|
||||
->where('p.status', 'pending')
|
||||
->where('p.openid', '<>', 'BALANCE')
|
||||
->where(function ($query) {
|
||||
$query->whereNull('p.last_sync_time')->whereOr('p.last_sync_time', '<', time() - 60);
|
||||
})
|
||||
->field('p.out_trade_no')->order('p.id asc')->limit(100)->select();
|
||||
foreach ($pending as $payment) {
|
||||
try {
|
||||
PaymentService::confirmOrderPay((string)$payment['out_trade_no']);
|
||||
} catch (\Throwable $e) {
|
||||
\think\Log::error('[OrderRefundRetry payment] ' . $payment['out_trade_no'] . ' ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
$orders = Db::name('pay_order')->alias('p')->join('order o', 'o.id = p.order_id')
|
||||
->where('o.status', OrderStatus::CANCELLED)
|
||||
->whereIn('p.status', ['paid', 'refunding', 'refund_failed'])
|
||||
->where('p.updatetime', '<', time() - 60)
|
||||
->field('o.id')->group('o.id')->order('o.id asc')->limit(100)->select();
|
||||
foreach ($orders as $order) {
|
||||
$id = (int)$order['id'];
|
||||
try {
|
||||
PaymentService::refundOrder($id, '取消订单原路退款恢复');
|
||||
PaymentService::syncCancelledOrderRefund($id);
|
||||
$output->writeln('订单 #' . $id . ' 已核对退款');
|
||||
} catch (\Throwable $e) {
|
||||
PaymentService::syncCancelledOrderRefund($id);
|
||||
\think\Log::error('[OrderRefundRetry] order_id=' . $id . ' ' . $e->getMessage());
|
||||
$output->writeln('订单 #' . $id . ' 退款异常:' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,7 @@ class PayOrder extends Backend
|
||||
}
|
||||
try {
|
||||
$after = PaymentService::syncRefundPayOrder($id);
|
||||
PaymentService::syncCancelledOrderRefund((int)$po['order_id']);
|
||||
} catch (\Throwable $e) {
|
||||
$this->error('同步微信状态失败:' . $e->getMessage());
|
||||
return;
|
||||
@@ -103,6 +104,7 @@ class PayOrder extends Backend
|
||||
}
|
||||
try {
|
||||
$after = PaymentService::refundSinglePayOrder($id, '平台人工重发原路退款(退款台账)');
|
||||
PaymentService::syncCancelledOrderRefund((int)$po['order_id']);
|
||||
} catch (\Throwable $e) {
|
||||
$this->error('重发退款失败:' . $e->getMessage());
|
||||
return;
|
||||
|
||||
@@ -370,12 +370,6 @@ class Auth extends Base
|
||||
if (!$master) {
|
||||
$this->error('请先完成师傅入驻', ['need_apply' => 1], 2001);
|
||||
}
|
||||
if ($master['verify_status'] === 'pending') {
|
||||
$this->error('师傅资质审核中,请耐心等待', ['verify_status' => 'pending'], 2002);
|
||||
}
|
||||
if ($master['verify_status'] === 'reject') {
|
||||
$this->error('资质未通过:' . $master['audit_msg'], ['verify_status' => 'reject'], 2003);
|
||||
}
|
||||
}
|
||||
|
||||
if ($role === 'merchant') {
|
||||
|
||||
@@ -51,20 +51,30 @@ class Base extends Api
|
||||
}
|
||||
|
||||
/**
|
||||
* 要求是已通过审核的师傅
|
||||
* 要求拥有师傅档案,允许查看师傅端。
|
||||
*/
|
||||
protected function requireMaster()
|
||||
protected function requireMasterProfile()
|
||||
{
|
||||
$master = $this->masterInfo();
|
||||
if (!$master) {
|
||||
$this->error('请先完成师傅入驻', ['need_apply' => 1], 2001);
|
||||
}
|
||||
return $master;
|
||||
}
|
||||
|
||||
/** 要求师傅通过审核,供接单及敏感操作使用。 */
|
||||
protected function requireMaster()
|
||||
{
|
||||
$master = $this->requireMasterProfile();
|
||||
if ($master['verify_status'] === 'pending') {
|
||||
$this->error('师傅资质审核中,请耐心等待', ['verify_status' => 'pending'], 2002);
|
||||
}
|
||||
if ($master['verify_status'] === 'reject') {
|
||||
$this->error('资质未通过:' . $master['audit_msg'], ['verify_status' => 'reject'], 2003);
|
||||
}
|
||||
if ($master['verify_status'] !== 'pass') {
|
||||
$this->error('师傅资质尚未审核通过,无法接单');
|
||||
}
|
||||
return $master;
|
||||
}
|
||||
|
||||
@@ -145,7 +155,10 @@ class Base extends Api
|
||||
'status' => (int)$to,
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
Db::name('order')->where('id', (int)$order['id'])->update($data);
|
||||
$updated = Db::name('order')->where('id', (int)$order['id'])->where('status', $from)->update($data);
|
||||
if (!$updated) {
|
||||
$this->error('订单状态已变更,请刷新后重试');
|
||||
}
|
||||
$this->addLog((int)$order['id'], (int)$to, $remark, $operatorType, $operatorId);
|
||||
return array_merge($order, $data);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace app\api\controller;
|
||||
|
||||
use app\common\library\CommissionService;
|
||||
use app\common\library\FinanceConfigService;
|
||||
use app\common\library\FinishImageUrls;
|
||||
use app\common\library\OrderStatus;
|
||||
use app\common\library\PaymentService;
|
||||
use app\common\library\TiandituService;
|
||||
@@ -98,11 +99,9 @@ class Master extends Base
|
||||
}
|
||||
|
||||
// 若是驳回后重提且未修改脱敏展示号,沿用原存储的完整身份证号;否则校验完整身份证号并真实入库
|
||||
$needVerify = true;
|
||||
if (strpos($rawIdcard, '*') !== false) {
|
||||
if ($exist && !empty($exist['idcard_no']) && strpos((string)$exist['idcard_no'], '*') === false) {
|
||||
$finalIdcard = (string)$exist['idcard_no'];
|
||||
$needVerify = false;
|
||||
} else {
|
||||
$this->error('请填写真实完整的18位身份证号码');
|
||||
return;
|
||||
@@ -125,12 +124,10 @@ class Master extends Base
|
||||
}
|
||||
|
||||
// 腾讯云公安权威二要素实名核验(姓名 + 身份证号)
|
||||
if ($needVerify) {
|
||||
$verifyRes = TencentVerifyService::verifyIdCard($realname, $finalIdcard);
|
||||
if (!$verifyRes['pass']) {
|
||||
$this->error('实名核验未通过:' . $verifyRes['msg']);
|
||||
return;
|
||||
}
|
||||
$verifyRes = TencentVerifyService::verifyIdCard($realname, $finalIdcard);
|
||||
if (!$verifyRes['pass']) {
|
||||
$this->error('实名核验未通过:' . $verifyRes['msg']);
|
||||
return;
|
||||
}
|
||||
|
||||
$catNameMap = Db::name('service_cat')->where('id', 'in', $skillCatIds)->column('name', 'id');
|
||||
@@ -144,9 +141,10 @@ class Master extends Base
|
||||
'cert_images' => $certImages,
|
||||
'city' => $normalizedCity,
|
||||
'work_status' => 'off',
|
||||
'verify_status' => 'pass',
|
||||
'audit_msg' => '腾讯云二要素实名核验通过',
|
||||
'audittime' => time(),
|
||||
'verify_status' => 'pending',
|
||||
'audit_msg' => '',
|
||||
'audittime' => null,
|
||||
'audit_admin_id' => 0,
|
||||
'updatetime' => time(),
|
||||
];
|
||||
|
||||
@@ -180,7 +178,7 @@ class Master extends Base
|
||||
$this->error('提交失败:' . $e->getMessage());
|
||||
}
|
||||
|
||||
$this->success('实名认证成功,已获得接单资格!', ['master_id' => (int)$masterId]);
|
||||
$this->success('申请已提交,请等待后台审核', ['master_id' => (int)$masterId, 'verify_status' => 'pending']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -312,7 +310,7 @@ class Master extends Base
|
||||
*/
|
||||
public function updateLocation()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$rawLat = $this->request->post('lat', '');
|
||||
$rawLng = $this->request->post('lng', '');
|
||||
if (!$this->isValidCoord($rawLat, $rawLng)) {
|
||||
@@ -389,7 +387,7 @@ class Master extends Base
|
||||
*/
|
||||
public function searchLocation()
|
||||
{
|
||||
$this->requireMaster();
|
||||
$this->requireMasterProfile();
|
||||
$keyword = trim((string)$this->request->param('keyword', ''));
|
||||
if (mb_strlen($keyword) < 2) {
|
||||
$this->success('', ['list' => []]);
|
||||
@@ -410,7 +408,7 @@ class Master extends Base
|
||||
*/
|
||||
public function locationContext()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$rawLat = $this->request->param('lat', '');
|
||||
$rawLng = $this->request->param('lng', '');
|
||||
$category = trim((string)$this->request->param('category', 'all'));
|
||||
@@ -473,7 +471,7 @@ class Master extends Base
|
||||
*/
|
||||
public function locationOrderStats()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$rawLat = $this->request->param('lat', '');
|
||||
$rawLng = $this->request->param('lng', '');
|
||||
$city = trim((string)$this->request->param('city', ''));
|
||||
@@ -496,7 +494,7 @@ class Master extends Base
|
||||
*/
|
||||
public function locateCity()
|
||||
{
|
||||
$this->requireMaster();
|
||||
$this->requireMasterProfile();
|
||||
$city = trim((string)$this->request->param('city', ''));
|
||||
if ($city === '') {
|
||||
$this->error('请提供城市名称');
|
||||
@@ -529,7 +527,7 @@ class Master extends Base
|
||||
*/
|
||||
public function hall()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$this->recycleExpired();
|
||||
|
||||
$catIds = $this->getMasterSkillCatIds((int)$master['id']);
|
||||
@@ -989,7 +987,7 @@ class Master extends Base
|
||||
public function finish()
|
||||
{
|
||||
$order = $this->ownOrder((int)$this->request->post('order_id'), 'master');
|
||||
$images = (array)$this->request->post('images/a', []);
|
||||
$images = FinishImageUrls::normalize((array)$this->request->post('images/a', []));
|
||||
$damage = trim((string)$this->request->post('damage_remark', ''));
|
||||
|
||||
Db::startTrans();
|
||||
@@ -1142,7 +1140,7 @@ class Master extends Base
|
||||
|
||||
public function orders()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$status = $this->request->param('status', 'active');
|
||||
$page = max(1, (int)$this->request->param('page', 1));
|
||||
$limit = min(30, max(1, (int)$this->request->param('limit', 10)));
|
||||
@@ -1198,7 +1196,7 @@ class Master extends Base
|
||||
*/
|
||||
public function income()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
|
||||
// 顺带轻量同步最新 3 笔处理中的微信转账提现单(如师傅上次已确认收款但未回调或超时自动退回)
|
||||
$syncCandidates = Db::name('withdraw')
|
||||
@@ -1637,7 +1635,7 @@ class Master extends Base
|
||||
*/
|
||||
public function credit()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$mid = (int)$master['id'];
|
||||
|
||||
$reviewTotal = (int)Db::name('review')->where('master_id', $mid)->where('status', 'normal')->count();
|
||||
@@ -1671,7 +1669,7 @@ class Master extends Base
|
||||
*/
|
||||
public function appeals()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$list = Db::name('appeal')->where('master_id', $master['id'])->order('id desc')->limit(30)->select();
|
||||
$typeText = ['misjudge' => '误判申诉', 'review' => '恶意评价', 'deduct' => '扣款申诉', 'other' => '其他'];
|
||||
$statusText = ['wait' => '待处理', 'handling' => '处理中', 'done' => '已处理', 'reject' => '已驳回'];
|
||||
@@ -1749,7 +1747,7 @@ class Master extends Base
|
||||
*/
|
||||
public function quotes()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$list = Db::name('order_quote')->alias('q')
|
||||
->join('order o', 'o.id = q.order_id', 'LEFT')
|
||||
->field('q.*, o.order_no, o.service_name, o.pay_amount as order_amount, o.status as order_status')
|
||||
@@ -1994,7 +1992,7 @@ class Master extends Base
|
||||
|
||||
public function orderDetail()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$masterId = (int)$master['id'];
|
||||
$orderId = (int)$this->request->param('id') ?: (int)$this->request->param('order_id');
|
||||
if ($orderId <= 0) {
|
||||
@@ -2579,7 +2577,7 @@ class Master extends Base
|
||||
*/
|
||||
public function saveSkills()
|
||||
{
|
||||
$master = $this->requireMaster();
|
||||
$master = $this->requireMasterProfile();
|
||||
$masterId = (int)$master['id'];
|
||||
|
||||
// 同时兼容 skill_ids(ID 数组/逗号串/JSON串)与 selected_skills(名称数组/逗号串/JSON串)
|
||||
|
||||
@@ -1309,18 +1309,6 @@ class Order extends Base
|
||||
$this->error('该订单已开具发票,如需取消退款请联系客服办理发票冲红');
|
||||
}
|
||||
|
||||
// 若订单已支付,先在数据库事务外部调用微信支付 APIv3 逐笔发起原路退款(无有效流水严格拦截,严禁静默跳过)
|
||||
$refundedAmount = 0.00;
|
||||
if ((int)$order['pay_status'] === 1) {
|
||||
try {
|
||||
$refundedAmount = PaymentService::refundOrder($orderId, '用户取消:' . $reason);
|
||||
} catch (\Throwable $re) {
|
||||
\think\Log::error('[Order::cancel refund] order_id=' . $orderId . ' reason=' . $re->getMessage());
|
||||
$this->error('申请微信原路退款失败:' . $re->getMessage());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$prevMasterId = 0;
|
||||
Db::startTrans();
|
||||
try {
|
||||
@@ -1328,12 +1316,18 @@ class Order extends Base
|
||||
if (!$lockedOrder || !OrderStatus::canCancelByUser($lockedOrder['status'])) {
|
||||
throw new \InvalidArgumentException('当前状态不可取消,请刷新重试');
|
||||
}
|
||||
if (isset($lockedOrder['invoice_status']) && in_array($lockedOrder['invoice_status'], ['wait', 'issued'], true)) {
|
||||
throw new \InvalidArgumentException('订单开票状态已变更,请刷新后重试');
|
||||
}
|
||||
if ((int)$lockedOrder['pay_status'] === 1 && (float)$lockedOrder['pay_amount'] > 0) {
|
||||
$paymentAmount = (float)Db::name('pay_order')->where('order_id', $orderId)
|
||||
->whereIn('status', ['paid', 'refunding', 'refunded', 'refund_failed'])->sum('amount');
|
||||
if ($paymentAmount + 0.005 < (float)$lockedOrder['pay_amount']) {
|
||||
throw new \InvalidArgumentException('支付流水金额不足,请联系客服核实后取消');
|
||||
}
|
||||
}
|
||||
$prevMasterId = (int)$lockedOrder['master_id'];
|
||||
$extra = ['cancel_reason' => mb_substr($reason, 0, 255)];
|
||||
if ((int)$lockedOrder['pay_status'] === 1) {
|
||||
$extra['pay_status'] = 2;
|
||||
$extra['refund_amount'] = $refundedAmount > 0 ? $refundedAmount : (float)$lockedOrder['pay_amount'];
|
||||
}
|
||||
$this->transit($lockedOrder, OrderStatus::CANCELLED, '用户取消:' . $reason, $extra, 'user', $this->uid());
|
||||
|
||||
if ((int)$lockedOrder['coupon_id'] > 0) {
|
||||
@@ -1370,6 +1364,19 @@ class Order extends Base
|
||||
return;
|
||||
}
|
||||
|
||||
if ((int)$lockedOrder['pay_status'] === 1 && (float)$lockedOrder['pay_amount'] > 0) {
|
||||
try {
|
||||
PaymentService::refundOrder($orderId, '用户取消:' . $reason);
|
||||
PaymentService::syncCancelledOrderRefund($orderId);
|
||||
} catch (\Throwable $re) {
|
||||
\think\Log::error('[Order::cancel refund] order_id=' . $orderId . ' reason=' . $re->getMessage());
|
||||
PaymentService::syncCancelledOrderRefund($orderId);
|
||||
$this->success('订单已取消,退款申请异常,请联系客服处理');
|
||||
return;
|
||||
}
|
||||
$this->success('订单已取消,退款已申请,请留意退款进度');
|
||||
return;
|
||||
}
|
||||
$this->success('订单已取消');
|
||||
}
|
||||
|
||||
@@ -1614,7 +1621,16 @@ class Order extends Base
|
||||
$statusTimelineText = OrderStatus::tip($status);
|
||||
$statusTime = !empty($row['updatetime']) ? (int)$row['updatetime'] : (int)$row['createtime'];
|
||||
if ($status === OrderStatus::CANCELLED) {
|
||||
$statusTimelineText = ((int)$row['pay_status'] === 0) ? '订单未支付,您已取消订单' : '订单已取消,退款处理中';
|
||||
$refundRows = Db::name('pay_order')->where('order_id', (int)$row['id'])
|
||||
->whereIn('status', ['paid', 'refunding', 'refunded', 'refund_failed'])->select();
|
||||
$refundSummary = \app\common\library\CancelRefundSummary::summarize($refundRows);
|
||||
if ($refundSummary['state'] === 'missing') {
|
||||
$statusTimelineText = ((int)$row['pay_status'] === 0 || (float)$row['pay_amount'] <= 0)
|
||||
? '订单已取消' : '订单已取消,退款异常,请联系客服';
|
||||
} else {
|
||||
$refundTips = ['success' => '订单已取消,退款成功', 'processing' => '订单已取消,退款处理中', 'failed' => '订单已取消,退款异常,请联系客服'];
|
||||
$statusTimelineText = $refundTips[$refundSummary['state']];
|
||||
}
|
||||
} elseif ($status === OrderStatus::PENDING_PAY) {
|
||||
$statusTimelineText = '订单待支付,请尽快完成支付';
|
||||
} elseif ($status === OrderStatus::PENDING_ACCEPT) {
|
||||
|
||||
@@ -74,9 +74,11 @@ class Wxpay extends Api
|
||||
|
||||
try {
|
||||
PaymentService::applyWxRefundResult($po, $data);
|
||||
PaymentService::syncCancelledOrderRefund((int)$po['order_id']);
|
||||
} catch (\Throwable $refundEx) {
|
||||
// 若微信已下发明确退款异常/关闭终态,系统已完整落库记录原因并写入告警日志,向微信回传成功避免重复轰炸
|
||||
if (in_array($refStatus, ['ABNORMAL', 'CLOSED'], true)) {
|
||||
if (in_array($refStatus, ['ABNORMAL', 'CLOSED'], true) && (int)$refundEx->getCode() === 10001) {
|
||||
PaymentService::syncCancelledOrderRefund((int)$po['order_id']);
|
||||
Log::error("[Wxpay::refundNotify] 退款终态异常已落库 out_trade_no={$po['out_trade_no']}, status={$refStatus}, reason=" . $refundEx->getMessage());
|
||||
return $this->wxResponse(true);
|
||||
}
|
||||
|
||||
@@ -20,4 +20,5 @@ return [
|
||||
'app\admin\command\AttachmentScan',
|
||||
'app\admin\command\OrderAutoverify',
|
||||
'app\admin\command\OrderRecycle',
|
||||
'app\admin\command\OrderRefundRetry',
|
||||
];
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
namespace app\common\library;
|
||||
|
||||
class CancelRefundSummary
|
||||
{
|
||||
public static function summarize(array $rows)
|
||||
{
|
||||
$amount = 0.0;
|
||||
$state = $rows ? 'success' : 'missing';
|
||||
foreach ($rows as $row) {
|
||||
$amount += (float)$row['refund_amount'];
|
||||
if ($row['status'] === 'refund_failed') {
|
||||
$state = 'failed';
|
||||
} elseif ($row['status'] !== 'refunded' && $state !== 'failed') {
|
||||
$state = 'processing';
|
||||
}
|
||||
}
|
||||
return ['state' => $state, 'amount' => round($amount, 2)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
class FinishImageUrls
|
||||
{
|
||||
public static function normalize(array $images)
|
||||
{
|
||||
$urls = [];
|
||||
foreach ($images as $image) {
|
||||
if (!is_string($image)) {
|
||||
continue;
|
||||
}
|
||||
foreach (explode(',', $image) as $url) {
|
||||
$url = trim($url);
|
||||
if ($url !== '') {
|
||||
$urls[] = $url;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $urls;
|
||||
}
|
||||
}
|
||||
@@ -172,6 +172,9 @@ class PaymentService
|
||||
if (!$master) {
|
||||
throw new \InvalidArgumentException('报价师傅信息不存在');
|
||||
}
|
||||
if ($master['verify_status'] !== 'pass') {
|
||||
throw new \InvalidArgumentException('该师傅资质尚未审核通过,请选择其他师傅');
|
||||
}
|
||||
|
||||
$quoteAmount = round((float)$quote['amount'], 2);
|
||||
$targetTotalPay = max(0, round($quoteAmount - (float)$order['discount_amount'], 2));
|
||||
@@ -517,6 +520,7 @@ class PaymentService
|
||||
if (
|
||||
!$quote
|
||||
|| !$master
|
||||
|| $master['verify_status'] !== 'pass'
|
||||
|| (int)$lockedOrder['status'] !== OrderStatus::QUOTING
|
||||
|| (int)$lockedOrder['master_id'] !== 0
|
||||
) {
|
||||
@@ -563,7 +567,7 @@ class PaymentService
|
||||
self::sendNotify('master', (int)$master['id'], '您的报价已被选中', '订单 ' . $lockedOrder['order_no'] . ' 客户已选择您的报价 ¥' . $quoteAmount . ' 并完成支付托管,请尽快联系客户', 'order', $orderId);
|
||||
}
|
||||
} elseif ($scene === 'diff') {
|
||||
if ((int)$lockedOrder['diff_status'] !== 1) {
|
||||
if ((int)$lockedOrder['diff_status'] !== 1 || (int)$lockedOrder['status'] === OrderStatus::CANCELLED) {
|
||||
$autoRefundDuplicate = true;
|
||||
} else {
|
||||
$diffAmount = round((float)$lockedPay['amount'], 2);
|
||||
@@ -607,6 +611,7 @@ class PaymentService
|
||||
self::addOrderLog((int)$payOrder['order_id'], 0, '【高危财务异常】' . $duplicateRefundError, 'system', (int)$payOrder['user_id']);
|
||||
Log::error('[PaymentService::confirmOrderPay] ' . $duplicateRefundError);
|
||||
}
|
||||
self::syncCancelledOrderRefund((int)$payOrder['order_id']);
|
||||
}
|
||||
|
||||
// 事务外:新工单广播给在线认证师傅
|
||||
@@ -672,29 +677,72 @@ class PaymentService
|
||||
}
|
||||
|
||||
$totalRefunded = 0.00;
|
||||
$errors = [];
|
||||
foreach ($effectiveRows as $po) {
|
||||
if ($po['status'] === 'refunded') {
|
||||
// 已退满:直接累计已退金额(含此前部分退款累计)
|
||||
$totalRefunded = round($totalRefunded + (float)$po['refund_amount'], 2);
|
||||
continue;
|
||||
}
|
||||
if ($po['status'] === 'refunding') {
|
||||
$synced = self::syncRefundPayOrder((int)$po['id']);
|
||||
if ($synced['status'] === 'refund_failed') {
|
||||
throw new \RuntimeException('历史退款单(' . $synced['refund_no'] . ')微信侧退款异常:' . $synced['fail_reason']);
|
||||
try {
|
||||
if ($po['status'] === 'refunded') {
|
||||
// 已退满:直接累计已退金额(含此前部分退款累计)
|
||||
$totalRefunded = round($totalRefunded + (float)$po['refund_amount'], 2);
|
||||
continue;
|
||||
}
|
||||
// 以同步后流水的累计已退金额为准(准确支持部分退款累计)
|
||||
$totalRefunded = round($totalRefunded + (float)$synced['refund_amount'], 2);
|
||||
continue;
|
||||
if ($po['status'] === 'refunding') {
|
||||
$synced = self::syncRefundPayOrder((int)$po['id']);
|
||||
if ($synced['status'] === 'refund_failed') {
|
||||
throw new \RuntimeException('历史退款单(' . $synced['refund_no'] . ')微信侧退款异常:' . $synced['fail_reason']);
|
||||
}
|
||||
$totalRefunded = round($totalRefunded + (float)$synced['refund_amount'], 2);
|
||||
continue;
|
||||
}
|
||||
// paid 或 refund_failed 自动退还该笔流水的全部剩余可退金额。
|
||||
$after = self::refundSinglePayOrder((int)$po['id'], $reason);
|
||||
$totalRefunded = round($totalRefunded + (float)($after['refund_amount'] ?: $po['amount']), 2);
|
||||
} catch (\Throwable $e) {
|
||||
if ((int)$e->getCode() !== 409) {
|
||||
Db::name('pay_order')->where('id', (int)$po['id'])->where('status', 'paid')->update([
|
||||
'status' => 'refund_failed',
|
||||
'fail_reason' => mb_substr('取消订单退款申请失败:' . $e->getMessage(), 0, 480),
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
}
|
||||
$errors[] = '支付流水 ' . $po['id'] . ':' . $e->getMessage();
|
||||
}
|
||||
// paid 或 refund_failed 均发起/重试原路退款(自动退该笔流水全部剩余可退金额)
|
||||
$after = self::refundSinglePayOrder((int)$po['id'], $reason);
|
||||
$totalRefunded = round($totalRefunded + (float)($after['refund_amount'] ?: $po['amount']), 2);
|
||||
}
|
||||
|
||||
if ($errors) {
|
||||
throw new \RuntimeException(implode(';', $errors));
|
||||
}
|
||||
|
||||
return $totalRefunded;
|
||||
}
|
||||
|
||||
/** 汇总已取消订单的真实退款结果;事务内只读取支付流水,绝不调用外部服务。 */
|
||||
public static function syncCancelledOrderRefund($orderId)
|
||||
{
|
||||
Db::startTrans();
|
||||
try {
|
||||
$order = Db::name('order')->where('id', (int)$orderId)->lock(true)->find();
|
||||
if (!$order || (int)$order['status'] !== OrderStatus::CANCELLED) {
|
||||
Db::commit();
|
||||
return null;
|
||||
}
|
||||
$rows = Db::name('pay_order')->where('order_id', (int)$orderId)
|
||||
->whereIn('status', ['paid', 'refunding', 'refunded', 'refund_failed'])->select();
|
||||
$summary = CancelRefundSummary::summarize($rows);
|
||||
if ($summary['state'] !== 'missing') {
|
||||
Db::name('order')->where('id', (int)$orderId)->update([
|
||||
'refund_amount' => $summary['amount'],
|
||||
'pay_status' => $summary['state'] === 'success' ? 2 : 1,
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
}
|
||||
Db::commit();
|
||||
return $summary;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 售后部分退款:按指定退款总额在订单名下有效支付流水间依次原路退回(必须在事务外部调用)
|
||||
*
|
||||
@@ -816,6 +864,20 @@ class PaymentService
|
||||
* @return array 更新后的 pay_order 记录
|
||||
*/
|
||||
public static function refundSinglePayOrder($payOrderId, $reason = '订单取消原路退款', $partialAmount = null)
|
||||
{
|
||||
$lockName = 'yjyf_refund_' . (int)$payOrderId;
|
||||
$rows = Db::query('SELECT GET_LOCK(?, 2) AS acquired', [$lockName]);
|
||||
if (empty($rows) || (int)$rows[0]['acquired'] !== 1) {
|
||||
throw new \RuntimeException('该支付流水正在退款处理中,请稍后重试', 409);
|
||||
}
|
||||
try {
|
||||
return self::refundSinglePayOrderLocked($payOrderId, $reason, $partialAmount);
|
||||
} finally {
|
||||
Db::query('SELECT RELEASE_LOCK(?)', [$lockName]);
|
||||
}
|
||||
}
|
||||
|
||||
protected static function refundSinglePayOrderLocked($payOrderId, $reason, $partialAmount)
|
||||
{
|
||||
$po = Db::name('pay_order')->where('id', (int)$payOrderId)->find();
|
||||
if (!$po) {
|
||||
@@ -831,6 +893,24 @@ class PaymentService
|
||||
throw new \InvalidArgumentException('当前支付单状态(' . self::payOrderStatusLabel($po['status']) . ')不允许发起退款');
|
||||
}
|
||||
|
||||
// 对请求超时等未知结果先查微信;仅明确不存在时使用原退款单号重新提交。
|
||||
if ($po['status'] === 'refund_failed' && $po['openid'] !== 'BALANCE'
|
||||
&& strpos((string)$po['out_trade_no'], 'BAL') !== 0 && !empty($po['refund_no'])
|
||||
&& !in_array($po['refund_status'], ['abnormal', 'closed'], true)) {
|
||||
try {
|
||||
$po = self::syncRefundPayOrder((int)$po['id']);
|
||||
if (in_array($po['status'], ['refunding', 'refunded'], true)) {
|
||||
return $po;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$fail = WxPayV3Service::extractFailInfo($e);
|
||||
if ($fail['code'] !== 'RESOURCE_NOT_EXISTS') {
|
||||
throw $e;
|
||||
}
|
||||
$po = Db::name('pay_order')->where('id', (int)$po['id'])->find();
|
||||
}
|
||||
}
|
||||
|
||||
// 可退余额 = 流水支付总额 - 已累计成功退款金额(支持一笔流水多次部分退款)
|
||||
$payTotal = round((float)$po['amount'], 2);
|
||||
$refundable = round($payTotal - round((float)$po['refund_amount'], 2), 2);
|
||||
@@ -942,7 +1022,7 @@ class PaymentService
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return self::applyWxRefundResult($po, $resp, round((float)$po['amount'], 2));
|
||||
return self::applyWxRefundResult($po, $resp);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -953,6 +1033,52 @@ class PaymentService
|
||||
* 累计退满后流水状态置为 refunded,未退满则保持 paid 可继续发起退款。
|
||||
*/
|
||||
public static function applyWxRefundResult(array $po, array $wxRefundData, $fallbackAmount = 0.00)
|
||||
{
|
||||
Db::startTrans();
|
||||
$transactionClosed = false;
|
||||
try {
|
||||
$locked = Db::name('pay_order')->where('id', (int)$po['id'])->lock(true)->find();
|
||||
if (!$locked) {
|
||||
throw new \RuntimeException('支付交易单不存在');
|
||||
}
|
||||
$incomingNo = trim((string)($wxRefundData['out_refund_no'] ?? ''));
|
||||
if ($incomingNo !== '' && $incomingNo !== (string)$locked['refund_no']) {
|
||||
throw new \RuntimeException('退款通知的退款单号与当前退款单不一致');
|
||||
}
|
||||
$incomingId = trim((string)($wxRefundData['refund_id'] ?? ''));
|
||||
$wxStatus = strtoupper(trim((string)($wxRefundData['status'] ?? $wxRefundData['refund_status'] ?? '')));
|
||||
if ($wxStatus === 'SUCCESS' && $incomingId === '') {
|
||||
throw new \RuntimeException('微信退款成功报文缺少退款单号,无法安全核对');
|
||||
}
|
||||
if ($incomingId !== '' && $locked['refund_status'] === 'success'
|
||||
&& $incomingId === (string)$locked['refund_id']) {
|
||||
Db::commit();
|
||||
$transactionClosed = true;
|
||||
return $locked;
|
||||
}
|
||||
try {
|
||||
$result = self::applyWxRefundResultLocked($locked, $wxRefundData, $fallbackAmount);
|
||||
} catch (\Throwable $e) {
|
||||
if (in_array($wxStatus, ['ABNORMAL', 'CLOSED'], true) && (int)$e->getCode() === 10001) {
|
||||
Db::commit();
|
||||
} else {
|
||||
Db::rollback();
|
||||
}
|
||||
$transactionClosed = true;
|
||||
throw $e;
|
||||
}
|
||||
Db::commit();
|
||||
$transactionClosed = true;
|
||||
return $result;
|
||||
} catch (\Throwable $e) {
|
||||
if (!$transactionClosed) {
|
||||
Db::rollback();
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
protected static function applyWxRefundResultLocked(array $po, array $wxRefundData, $fallbackAmount = 0.00)
|
||||
{
|
||||
$wxStatus = strtoupper(trim((string)($wxRefundData['status'] ?? $wxRefundData['refund_status'] ?? '')));
|
||||
if ($wxStatus === '') {
|
||||
@@ -967,10 +1093,16 @@ class PaymentService
|
||||
if ($thisRefund <= 0) {
|
||||
$thisRefund = round((float)$fallbackAmount, 2);
|
||||
}
|
||||
if ($wxStatus === 'SUCCESS' && $thisRefund <= 0) {
|
||||
throw new \RuntimeException('微信退款成功报文缺少退款金额,无法安全核对');
|
||||
}
|
||||
// 此前已完成的部分退款累计(PROCESSING 阶段不写入本次金额,避免同步到账后重复累计)
|
||||
$prevRefunded = round((float)$po['refund_amount'], 2);
|
||||
|
||||
if ($wxStatus === 'SUCCESS') {
|
||||
if ($prevRefunded + $thisRefund > $payTotal + 0.005) {
|
||||
throw new \RuntimeException('退款金额超过支付流水可退余额,请人工核查');
|
||||
}
|
||||
$succTime = !empty($wxRefundData['success_time'])
|
||||
? (strtotime((string)$wxRefundData['success_time']) ?: $now)
|
||||
: $now;
|
||||
@@ -1027,7 +1159,7 @@ class PaymentService
|
||||
self::addOrderLog((int)$po['order_id'], 0, '【退款异常告警】' . $reasonZh . '(退款单号:' . $po['refund_no'] . ')', 'system', 0);
|
||||
Log::error("[PaymentService::applyWxRefundResult] 退款失败 out_trade_no={$po['out_trade_no']}, refund_no={$po['refund_no']}, wxStatus={$wxStatus}");
|
||||
|
||||
throw new \RuntimeException($reasonZh);
|
||||
throw new \RuntimeException($reasonZh, 10001);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1898,7 +2030,7 @@ class PaymentService
|
||||
}
|
||||
$quote = Db::name('order_quote')->where('id', $quoteId)->where('order_id', $orderId)->lock(true)->find();
|
||||
$master = $quote ? Db::name('master')->where('id', (int)$quote['master_id'])->find() : null;
|
||||
if (!$quote || !$master || $quote['status'] !== 'wait') {
|
||||
if (!$quote || !$master || $master['verify_status'] !== 'pass' || $quote['status'] !== 'wait') {
|
||||
throw new \InvalidArgumentException('报价状态已变更,请刷新重试');
|
||||
}
|
||||
|
||||
|
||||
43
tests/cancel_balance_refund.php
普通文件
43
tests/cancel_balance_refund.php
普通文件
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
use app\common\library\PaymentService;
|
||||
use think\Db;
|
||||
|
||||
Db::startTrans();
|
||||
try {
|
||||
$user = Db::name('user')->where('id', 1)->find();
|
||||
if (!$user) throw new RuntimeException('Local test user missing');
|
||||
$order = Db::name('order')->find();
|
||||
if (!$order) throw new RuntimeException('Local test order template missing');
|
||||
$amount = 0.37;
|
||||
$trade = 'BALTEST' . bin2hex(random_bytes(8));
|
||||
unset($order['id']);
|
||||
$order['order_no'] = 'CANCELTEST' . bin2hex(random_bytes(6));
|
||||
$order['user_id'] = 1;
|
||||
$order['status'] = 9;
|
||||
$order['pay_status'] = 1;
|
||||
$order['pay_amount'] = $amount;
|
||||
$order['refund_amount'] = 0;
|
||||
$orderId = Db::name('order')->insertGetId($order);
|
||||
$id = Db::name('pay_order')->insertGetId([
|
||||
'out_trade_no' => $trade, 'order_id' => $orderId, 'order_no' => $order['order_no'],
|
||||
'user_id' => 1, 'scene' => 'order', 'openid' => 'BALANCE', 'amount' => $amount,
|
||||
'status' => 'paid', 'refund_status' => 'none',
|
||||
]);
|
||||
PaymentService::refundOrder($orderId, '取消订单退款测试');
|
||||
PaymentService::refundOrder($orderId, '取消订单退款测试');
|
||||
$summary = PaymentService::syncCancelledOrderRefund($orderId);
|
||||
$payment = Db::name('pay_order')->where('id', $id)->find();
|
||||
$after = Db::name('user')->where('id', 1)->find();
|
||||
$orderAfter = Db::name('order')->where('id', $orderId)->find();
|
||||
if ($payment['status'] !== 'refunded' || abs((float)$payment['refund_amount'] - $amount) > 0.001
|
||||
|| abs((float)$after['money'] - (float)$user['money'] - $amount) > 0.001
|
||||
|| (int)$orderAfter['pay_status'] !== 2 || $summary['state'] !== 'success') {
|
||||
throw new RuntimeException('Balance refund was not returned exactly once');
|
||||
}
|
||||
echo "Balance refund checks passed\n";
|
||||
} finally {
|
||||
Db::rollback();
|
||||
}
|
||||
11
tests/cancel_refund_summary.php
普通文件
11
tests/cancel_refund_summary.php
普通文件
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
require __DIR__ . '/../server/application/common/library/CancelRefundSummary.php';
|
||||
use app\common\library\CancelRefundSummary;
|
||||
function assertSummary($expected, $actual) {
|
||||
if ($actual !== $expected) throw new RuntimeException('Unexpected summary: ' . json_encode($actual));
|
||||
}
|
||||
assertSummary(['state' => 'processing', 'amount' => 0.0], CancelRefundSummary::summarize([['status' => 'refunding', 'refund_amount' => 0]]));
|
||||
assertSummary(['state' => 'failed', 'amount' => 4.0], CancelRefundSummary::summarize([['status' => 'refunded', 'refund_amount' => 4], ['status' => 'refund_failed', 'refund_amount' => 0]]));
|
||||
assertSummary(['state' => 'success', 'amount' => 10.0], CancelRefundSummary::summarize([['status' => 'refunded', 'refund_amount' => 4], ['status' => 'refunded', 'refund_amount' => 6]]));
|
||||
assertSummary(['state' => 'missing', 'amount' => 0.0], CancelRefundSummary::summarize([]));
|
||||
echo "Cancel refund summary checks passed\n";
|
||||
18
tests/finish_image_urls.php
普通文件
18
tests/finish_image_urls.php
普通文件
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
$path = getenv('MEDIA_NORMALIZER_PATH');
|
||||
if (!is_file($path)) { fwrite(STDERR, "FAIL: finish image normalizer is missing\n"); exit(1); }
|
||||
require $path;
|
||||
use app\common\library\FinishImageUrls;
|
||||
$a = 'https://example.test/one.jpg';
|
||||
$b = 'https://example.test/two.jpg';
|
||||
$cases = [
|
||||
[[$a . ',' . $b], [$a, $b]],
|
||||
[[$a, $b], [$a, $b]],
|
||||
[[$a], [$a]],
|
||||
[[], []],
|
||||
];
|
||||
foreach ($cases as $case) {
|
||||
$actual = FinishImageUrls::normalize($case[0]);
|
||||
if ($actual !== $case[1]) { fwrite(STDERR, "FAIL: " . json_encode($actual) . "\n"); exit(1); }
|
||||
}
|
||||
echo "finish image normalization passed\n";
|
||||
@@ -0,0 +1,24 @@
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
const assert = require('assert');
|
||||
const config = JSON.parse(fs.readFileSync('yjyf-app/pages.json', 'utf8'));
|
||||
const page = config.pages.find(p => p.path === 'pages/master/detail');
|
||||
assert.strictEqual(page.style.enablePullDownRefresh, true, '师傅工单详情应启用下拉刷新');
|
||||
const source = fs.readFileSync('yjyf-app/pages/master/detail.vue', 'utf8').match(/<script setup>([\s\S]*?)<\/script>/)[1].replace(/^\s*import .*;\s*$/gm, '');
|
||||
let refresh, load, stops = 0, requests = 0, fail = false, toast = '';
|
||||
const context = {
|
||||
ref: value => ({ value }), reactive: value => value, computed: fn => ({ get value() { return fn(); } }),
|
||||
getCurrentInstance: () => ({}), onLoad: fn => { load = fn; }, onShow() {}, onBeforeUnmount() {}, onPullDownRefresh: fn => { refresh = fn; },
|
||||
api: { masterOrderDetail: async id => { requests++; if (fail) throw { msg: '网络错误' }; return { id, status: 3 }; } },
|
||||
uni: { getLocation: opts => opts.fail(), stopPullDownRefresh: () => { stops++; }, showToast: opts => { toast = opts.title; } },
|
||||
setInterval: () => 1, clearInterval() {}, setTimeout() {}, Date, Number, String, Math, Promise
|
||||
};
|
||||
vm.runInNewContext(source + '\nthis.orderRef = order;', context);
|
||||
(async () => {
|
||||
load({ id: '123' });
|
||||
await refresh();
|
||||
assert.strictEqual(requests, 1); assert.strictEqual(context.orderRef.value.id, 123); assert.strictEqual(stops, 1);
|
||||
fail = true; await refresh();
|
||||
assert.strictEqual(requests, 2); assert.strictEqual(context.orderRef.value.id, 123); assert.strictEqual(stops, 2); assert.strictEqual(toast, '网络错误');
|
||||
console.log('师傅工单详情下拉刷新成功与失败流程通过');
|
||||
})().catch(e => { console.error(e); process.exitCode = 1; });
|
||||
@@ -0,0 +1,16 @@
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
const assert = require('assert');
|
||||
const source = fs.readFileSync('yjyf-app/pages/master/success.vue', 'utf8').match(/<script setup>([\s\S]*?)<\/script>/)[1].replace(/^\s*import .*;\s*$/gm, '');
|
||||
async function check(query) {
|
||||
let onLoadHandler;
|
||||
let submitted;
|
||||
const api = { masterOrderDetail: async () => ({}), masterSchedule: async data => { submitted = data; } };
|
||||
const context = { ref: value => ({ value }), onLoad: fn => { onLoadHandler = fn; }, api, uni: { showToast() {}, redirectTo() {} }, setTimeout() {}, Date, String, Number, Math };
|
||||
vm.runInNewContext(source + '\nthis.submitSchedule = submitSchedule;', context);
|
||||
onLoadHandler(query);
|
||||
await context.submitSchedule();
|
||||
assert.strictEqual(submitted.order_id, 123, `预约应保留入口订单编号: ${JSON.stringify(query)}`);
|
||||
assert.ok(submitted.appoint_time > 0);
|
||||
}
|
||||
(async () => { await check({ id: '123' }); await check({ order_id: '123' }); console.log('抢单成功页两个入口的预约参数验证通过'); })().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
namespace app\common\controller {
|
||||
class Api {
|
||||
protected function error($message) { throw new \RuntimeException($message); }
|
||||
}
|
||||
}
|
||||
namespace think {
|
||||
class Db {
|
||||
public static $status = 9;
|
||||
public static $logs = 0;
|
||||
public static function name($table) { return new Query($table); }
|
||||
}
|
||||
class Query {
|
||||
private $table;
|
||||
private $where = [];
|
||||
public function __construct($table) { $this->table = $table; }
|
||||
public function where($field, $value) { $this->where[$field] = $value; return $this; }
|
||||
public function update($data) {
|
||||
if (isset($this->where['status']) && $this->where['status'] !== Db::$status) return 0;
|
||||
Db::$status = $data['status'];
|
||||
return 1;
|
||||
}
|
||||
public function insert($data) { Db::$logs++; return 1; }
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
require __DIR__ . '/../server/application/common/library/OrderStatus.php';
|
||||
require __DIR__ . '/../server/application/api/controller/Base.php';
|
||||
class TransitionTest extends \app\api\controller\Base {
|
||||
public function runTransition($order) { return $this->transit($order, 5); }
|
||||
}
|
||||
$test = new TransitionTest();
|
||||
try {
|
||||
$test->runTransition(['id' => 1, 'status' => 3]);
|
||||
throw new \RuntimeException('Stale transition overwrote the cancelled order');
|
||||
} catch (\RuntimeException $e) {
|
||||
if ($e->getMessage() === 'Stale transition overwrote the cancelled order') throw $e;
|
||||
}
|
||||
if (\think\Db::$status !== 9 || \think\Db::$logs !== 0) throw new \RuntimeException('Cancelled order changed');
|
||||
\think\Db::$status = 3;
|
||||
$test->runTransition(['id' => 1, 'status' => 3]);
|
||||
if (\think\Db::$status !== 5 || \think\Db::$logs !== 1) throw new \RuntimeException('Valid transition failed');
|
||||
echo "Order transition concurrency checks passed\n";
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
use app\common\library\PaymentService;
|
||||
use think\Db;
|
||||
|
||||
Db::startTrans();
|
||||
try {
|
||||
$trade = 'TEST' . bin2hex(random_bytes(10));
|
||||
$refund = 'RF' . bin2hex(random_bytes(10));
|
||||
$id = Db::name('pay_order')->insertGetId([
|
||||
'out_trade_no' => $trade, 'order_id' => 2147483000, 'order_no' => 'REFUND-TEST',
|
||||
'user_id' => 1, 'scene' => 'order', 'openid' => 'TEST', 'amount' => '10.00',
|
||||
'status' => 'refunding', 'refund_no' => $refund, 'refund_status' => 'processing',
|
||||
]);
|
||||
$data = ['status' => 'SUCCESS', 'refund_id' => 'WXREFUNDTEST', 'out_refund_no' => $refund, 'amount' => ['refund' => 400]];
|
||||
$old = Db::name('pay_order')->where('id', $id)->find();
|
||||
PaymentService::applyWxRefundResult($old, $data);
|
||||
$current = Db::name('pay_order')->where('id', $id)->find();
|
||||
PaymentService::applyWxRefundResult($current, $data);
|
||||
$after = Db::name('pay_order')->where('id', $id)->find();
|
||||
if ((float)$after['refund_amount'] !== 4.0 || $after['status'] !== 'paid') {
|
||||
throw new RuntimeException('Duplicate refund callback counted more than once');
|
||||
}
|
||||
PaymentService::applyWxRefundResult($old, $data);
|
||||
$processing = $data; $processing['status'] = 'PROCESSING';
|
||||
PaymentService::applyWxRefundResult($old, $processing);
|
||||
$after = Db::name('pay_order')->where('id', $id)->find();
|
||||
if ((float)$after['refund_amount'] !== 4.0 || $after['status'] !== 'paid') {
|
||||
throw new RuntimeException('Stale callback changed an already completed refund');
|
||||
}
|
||||
$id2 = Db::name('pay_order')->insertGetId([
|
||||
'out_trade_no' => $trade . 'B', 'order_id' => 2147483000, 'order_no' => 'REFUND-TEST',
|
||||
'user_id' => 1, 'scene' => 'order', 'openid' => 'TEST', 'amount' => '10.00',
|
||||
'status' => 'refunding', 'refund_no' => $refund . 'B', 'refund_status' => 'processing',
|
||||
]);
|
||||
$failed = ['status' => 'ABNORMAL', 'refund_id' => 'WXFAILTEST', 'out_refund_no' => $refund . 'B'];
|
||||
try {
|
||||
PaymentService::applyWxRefundResult(Db::name('pay_order')->where('id', $id2)->find(), $failed);
|
||||
throw new RuntimeException('Abnormal refund was accepted');
|
||||
} catch (RuntimeException $e) {
|
||||
if ($e->getMessage() === 'Abnormal refund was accepted') throw $e;
|
||||
}
|
||||
$failedRow = Db::name('pay_order')->where('id', $id2)->find();
|
||||
if ($failedRow['status'] !== 'refund_failed' || (float)$failedRow['refund_amount'] !== 0.0) {
|
||||
throw new RuntimeException('Abnormal refund was not recorded correctly');
|
||||
}
|
||||
echo "Refund callback idempotency checks passed\n";
|
||||
} finally {
|
||||
Db::rollback();
|
||||
}
|
||||
17
tests/refund_recovery_query.php
普通文件
17
tests/refund_recovery_query.php
普通文件
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
use app\common\library\OrderStatus;
|
||||
use think\Db;
|
||||
|
||||
$base = Db::name('pay_order')->alias('p')->join('order o', 'o.id = p.order_id')
|
||||
->where('o.status', OrderStatus::CANCELLED)->where('p.id', 0);
|
||||
$base->where('p.status', 'pending')->where('p.openid', '<>', 'BALANCE')
|
||||
->where(function ($q) { $q->whereNull('p.last_sync_time')->whereOr('p.last_sync_time', '<', time() - 60); })
|
||||
->field('p.out_trade_no')->order('p.id asc')->limit(100)->select();
|
||||
Db::name('pay_order')->alias('p')->join('order o', 'o.id = p.order_id')
|
||||
->where('o.status', OrderStatus::CANCELLED)->where('p.id', 0)
|
||||
->whereIn('p.status', ['paid', 'refunding', 'refund_failed'])
|
||||
->where('p.updatetime', '<', time() - 60)->field('o.id')->group('o.id')->order('o.id asc')->limit(100)->select();
|
||||
echo "Refund recovery queries passed\n";
|
||||
@@ -777,7 +777,7 @@
|
||||
|
||||
if (meResult.status === 'fulfilled' && meResult.value) {
|
||||
const meRes = meResult.value;
|
||||
if (!meRes.applied || meRes.master?.verify_status !== 'pass') {
|
||||
if (!meRes.applied || !meRes.master) {
|
||||
uni.redirectTo({ url: '/pages/master/apply' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -50,11 +50,11 @@
|
||||
<view class="profile-hero" :style="{ backgroundPosition: '0 -' + navHeight + 'px' }">
|
||||
<view class="hero-body">
|
||||
<view class="user-block">
|
||||
<view class="avatar-wrap clickable-hover" @tap="go('/pages/master/auth')">
|
||||
<view class="avatar-wrap clickable-hover" @tap="go('/pages/master/apply')">
|
||||
<image class="avatar-img" src="/static/icons/avatar-master.svg" mode="aspectFit" />
|
||||
<view class="v-auth-badge">
|
||||
<image class="v-badge-ico" src="/static/icons/v-auth.svg" mode="aspectFit" />
|
||||
<text class="v-badge-txt">已实名</text>
|
||||
<text class="v-badge-txt">{{ verifyStatusMeta.text }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="user-meta">
|
||||
@@ -192,7 +192,7 @@
|
||||
|
||||
<!-- 5. 资质与平台支持菜单组 -->
|
||||
<view class="menu-card">
|
||||
<view class="menu-item clickable-hover" @tap="go('/pages/master/auth')">
|
||||
<view class="menu-item clickable-hover" @tap="go('/pages/master/apply')">
|
||||
<view class="mi-left">
|
||||
<image class="mi-ico" src="/static/icons/master/menu-auth.svg" mode="aspectFit" />
|
||||
<text class="mi-title">实名认证</text>
|
||||
@@ -452,7 +452,7 @@
|
||||
|
||||
if (infoRes.status === 'fulfilled' && infoRes.value) {
|
||||
const res = infoRes.value;
|
||||
if (!res.applied || !res.master || res.master.verify_status !== 'pass') {
|
||||
if (!res.applied || !res.master) {
|
||||
uni.redirectTo({ url: '/pages/master/apply' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -266,10 +266,10 @@
|
||||
return { title: '成为优匠优服师傅', desc: '实名认证 + 技能认证,接单赚收入', btn: '立即入驻', action: () => go('/pages/master/apply') };
|
||||
}
|
||||
if (m.verify_status === 'pending') {
|
||||
return { title: '师傅资质审核中', desc: '平台将在 1-2 个工作日内完成审核', btn: '查看进度', action: () => go('/pages/master/apply') };
|
||||
return { title: '师傅资质审核中', desc: '审核通过后可开启听单并接单', btn: '进入师傅端', action: switchToMaster };
|
||||
}
|
||||
if (m.verify_status === 'reject') {
|
||||
return { title: '师傅资质未通过', desc: m.audit_msg || '请补充资料后重新提交', btn: '重新提交', action: () => go('/pages/master/apply') };
|
||||
return { title: '师傅资质未通过', desc: m.audit_msg || '请补充资料后重新提交', btn: '进入师傅端', action: switchToMaster };
|
||||
}
|
||||
return { title: '师傅工作台', desc: '已通过认证,进入工作台开始接单', btn: '切换师傅端', action: switchToMaster };
|
||||
});
|
||||
|
||||
@@ -244,7 +244,7 @@
|
||||
},
|
||||
{
|
||||
"path": "pages/master/detail",
|
||||
"style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8" }
|
||||
"style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8", "enablePullDownRefresh": true }
|
||||
},
|
||||
{
|
||||
"path": "pages/master/success",
|
||||
|
||||
@@ -344,7 +344,7 @@
|
||||
/** 同步更新全局角色状态(师傅通过审核后下次登录默认直接进入师傅工作台) */
|
||||
function syncUserData(res) {
|
||||
const userinfo = (res && res.userinfo) || {};
|
||||
const isMasterPass = Boolean(userinfo.is_master && userinfo.master && userinfo.master.verify_status === 'pass');
|
||||
const isMasterPass = Boolean(userinfo.is_master && userinfo.master);
|
||||
|
||||
// 检查是否有特定指向业主端具体业务页面的重定向(排除首页、我的、登录页等通用页面)
|
||||
const isExplicitUserTarget = redirectUrl && (
|
||||
|
||||
@@ -197,7 +197,7 @@
|
||||
<text class="v">{{ info.master.order_count }} 单</text>
|
||||
</view>
|
||||
|
||||
<view class="go-btn clickable-hover" v-if="info.master.verify_status === 'pass'" @tap="goWorkbench">
|
||||
<view class="go-btn clickable-hover" @tap="goWorkbench">
|
||||
<text class="go-txt">进入师傅工作台</text>
|
||||
<image class="go-arrow" src="/static/icons/arrow-right-white.svg" mode="aspectFit" />
|
||||
</view>
|
||||
@@ -536,14 +536,10 @@
|
||||
};
|
||||
skills.value.forEach((id, i) => { payload['skills[' + i + ']'] = id; });
|
||||
await api.masterApply(payload);
|
||||
setRole('master');
|
||||
const u = getUser() || {};
|
||||
u.is_master = true;
|
||||
if (!u.master) u.master = {};
|
||||
u.master.verify_status = 'pass';
|
||||
u.master.can_take = true;
|
||||
const u = await api.profile();
|
||||
setUser(u);
|
||||
uni.showToast({ title: '实名认证成功!', icon: 'success' });
|
||||
setRole('master');
|
||||
uni.showToast({ title: '提交成功,等待审核', icon: 'success' });
|
||||
setTimeout(() => {
|
||||
uni.reLaunch({ url: '/pages/master/workbench' });
|
||||
}, 1200);
|
||||
|
||||
@@ -410,7 +410,7 @@
|
||||
|
||||
await api.masterApply(payload);
|
||||
uni.hideLoading();
|
||||
uni.showToast({ title: '实名认证成功!', icon: 'success' });
|
||||
uni.showToast({ title: '提交成功,等待审核', icon: 'success' });
|
||||
setTimeout(() => {
|
||||
uni.navigateBack({
|
||||
fail: () => uni.redirectTo({ url: '/pages/master/workbench' })
|
||||
|
||||
@@ -672,7 +672,7 @@
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed, onBeforeUnmount, getCurrentInstance } from 'vue';
|
||||
import { onLoad, onShow } from '@dcloudio/uni-app';
|
||||
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
|
||||
import YjyfNavBar from '@/components/YjyfNavBar.vue';
|
||||
import YjyfServicePopup from '@/components/YjyfServicePopup.vue';
|
||||
import api from '@/utils/api.js';
|
||||
@@ -1194,7 +1194,7 @@
|
||||
try {
|
||||
await api.masterGrab({ order_id: order.value.id });
|
||||
uni.redirectTo({
|
||||
url: `/pages/master/success?id=${order.value.id}`,
|
||||
url: `/pages/master/success?order_id=${order.value.id}`,
|
||||
complete: () => { submitting.value = false; }
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -1277,6 +1277,17 @@
|
||||
}
|
||||
});
|
||||
|
||||
onPullDownRefresh(async () => {
|
||||
try {
|
||||
await loadDetail();
|
||||
if (loadError.value && order.value) {
|
||||
uni.showToast({ title: loadError.value, icon: 'none' });
|
||||
}
|
||||
} finally {
|
||||
uni.stopPullDownRefresh();
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (timer) clearInterval(timer);
|
||||
});
|
||||
|
||||
@@ -99,8 +99,8 @@
|
||||
const appointSlot = ref(timeSlots[1]);
|
||||
|
||||
onLoad((query) => {
|
||||
if (query && query.order_id) {
|
||||
orderId.value = Number(query.order_id);
|
||||
if (query && (query.order_id || query.id)) {
|
||||
orderId.value = Number(query.order_id || query.id);
|
||||
}
|
||||
if (query && query.mobile) {
|
||||
userMobile.value = query.mobile;
|
||||
|
||||
在新工单中引用
屏蔽一个用户