|
|
|
|
@ -1550,10 +1550,57 @@ class OrdersController extends CommonController
|
|
|
|
|
|
|
|
|
|
DB::beginTransaction();
|
|
|
|
|
try {
|
|
|
|
|
// 1. 获取订单的微信支付记录
|
|
|
|
|
$recharges = (new Recharge())
|
|
|
|
|
->where("order_id", $order->id)
|
|
|
|
|
->whereNotNull("paid_at")
|
|
|
|
|
->doesntHave("refunds")
|
|
|
|
|
->whereIn("payment", "weixin")
|
|
|
|
|
->get();
|
|
|
|
|
|
|
|
|
|
// 2. 计算支付总额
|
|
|
|
|
$totalPaid = $recharges->sum('money');
|
|
|
|
|
|
|
|
|
|
// 3. 获取用户当前余额
|
|
|
|
|
$customer = $order->customer;
|
|
|
|
|
$currentBalance = $customer->balance;
|
|
|
|
|
|
|
|
|
|
// 4. 如果支付总额等于用户余额,进行退款处理
|
|
|
|
|
if ($totalPaid > 0 && $totalPaid == $currentBalance) {
|
|
|
|
|
foreach ($recharges as $recharge) {
|
|
|
|
|
// 更新用户余额
|
|
|
|
|
$currentBalance -= $recharge->money;
|
|
|
|
|
$customer->balance = $currentBalance;
|
|
|
|
|
$customer->save();
|
|
|
|
|
// 生成退款记录与财务记录
|
|
|
|
|
$refund = Refund::create([
|
|
|
|
|
"customer_id" => $order->customer->id,
|
|
|
|
|
"money" => $recharge->money,
|
|
|
|
|
"order_id" => $order->id,
|
|
|
|
|
"payment" => $recharge->payment,
|
|
|
|
|
"recharge_id" => $recharge->id,
|
|
|
|
|
"merchant_id" => $recharge->merchant_id,
|
|
|
|
|
"remark" => "取消订单,自动退款"
|
|
|
|
|
]);
|
|
|
|
|
$refund->getSerial();
|
|
|
|
|
|
|
|
|
|
$balance = Balance::create([
|
|
|
|
|
"customer_id" => $customer->id,
|
|
|
|
|
"order_id" => $order->id,
|
|
|
|
|
"belongs_type" => get_class($refund),
|
|
|
|
|
"belongs_id" => $refund->id,
|
|
|
|
|
"money" => -$refund->money,
|
|
|
|
|
"balance" => $currentBalance
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 5. 删除订单及子订单
|
|
|
|
|
foreach ($order->orderItems as $orderItem) {
|
|
|
|
|
$orderItem->delete();
|
|
|
|
|
}
|
|
|
|
|
$order->delete();
|
|
|
|
|
|
|
|
|
|
DB::commit();
|
|
|
|
|
return response()->json($order);
|
|
|
|
|
} catch (\Exception $exception) {
|
|
|
|
|
|