|
|
@@ -16,37 +16,55 @@ class OrderCancelHandler
|
|
|
*/
|
|
|
public function afterCancelOrder($order)
|
|
|
{
|
|
|
- if (!$order) {
|
|
|
+ if (! $order || ! $order->giftcard_number) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
- // 检查订单是否使用了礼品卡
|
|
|
- if (!$order->giftcard_number || !$order->giftcard_amount || $order->giftcard_amount <= 0) {
|
|
|
+ // 以订单固化的 base 金额回补,缺失时退回用当前币种转换(保持兼容)
|
|
|
+ $refundAmount = (float) ($order->base_giftcard_amount ?? 0);
|
|
|
+ if ($refundAmount <= 0) {
|
|
|
+ $refundAmount = (float) core()->convertToBasePrice($order->giftcard_amount ?? 0);
|
|
|
+ }
|
|
|
+
|
|
|
+ if ($refundAmount <= 0) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
$giftCardNumber = $order->giftcard_number;
|
|
|
- $refundAmount = core()->convertToBasePrice($order->giftcard_amount);
|
|
|
|
|
|
- // 查找礼品卡
|
|
|
$giftCard = GiftCards::where('giftcard_number', $giftCardNumber)->first();
|
|
|
|
|
|
- if (!$giftCard) {
|
|
|
+ if (! $giftCard) {
|
|
|
return;
|
|
|
}
|
|
|
- // 记录退款前余额
|
|
|
- $balanceBefore = $giftCard->remaining_giftcard_amount;
|
|
|
- // 恢复礼品卡余额
|
|
|
- $giftCard->used_giftcard_amount = max(0, $giftCard->used_giftcard_amount - $refundAmount);
|
|
|
- $giftCard->remaining_giftcard_amount += $refundAmount;
|
|
|
|
|
|
- // 恢复状态为未使用
|
|
|
- if ($giftCard->remaining_giftcard_amount > 0) {
|
|
|
- $giftCard->giftcard_status = 1; // 未使用
|
|
|
+ // 幂等:同一订单已经退过款就不再重复回补(force 取消 / 重试场景)
|
|
|
+ $alreadyRefunded = GiftCardUsageLog::where('order_id', $order->id)
|
|
|
+ ->where('giftcard_number', $giftCardNumber)
|
|
|
+ ->where('action_type', GiftCardUsageLog::ACTION_REFUND)
|
|
|
+ ->exists();
|
|
|
+
|
|
|
+ if ($alreadyRefunded) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ $balanceBefore = (float) $giftCard->remaining_giftcard_amount;
|
|
|
+
|
|
|
+ $giftCard->used_giftcard_amount = max(0, (float) $giftCard->used_giftcard_amount - $refundAmount);
|
|
|
+ // 回补封顶到卡面额,防止重复/异常退款把余额补超
|
|
|
+ $giftCard->remaining_giftcard_amount = min(
|
|
|
+ (float) $giftCard->giftcard_amount,
|
|
|
+ (float) $giftCard->remaining_giftcard_amount + $refundAmount
|
|
|
+ );
|
|
|
+
|
|
|
+ if ((float) $giftCard->remaining_giftcard_amount > 0) {
|
|
|
+ $giftCard->giftcard_status = $giftCard->isExpired()
|
|
|
+ ? GiftCards::STATUS_EXPIRED
|
|
|
+ : GiftCards::STATUS_UNUSED;
|
|
|
}
|
|
|
|
|
|
$giftCard->save();
|
|
|
- // 记录退款日志
|
|
|
+
|
|
|
GiftCardUsageLog::create([
|
|
|
'giftcard_number' => $giftCardNumber,
|
|
|
'customer_id' => $giftCard->customer_id,
|