discount_amount; if ($total <= 0 && !$order->coupon_id) { return; } $price = $order->plan()->first()?->prices[$order->period] ?? null; $percent = (int) $order->user()->value('discount'); $coupon = $order->coupon_id ? Coupon::find($order->coupon_id) : null; if ($price === null || ($order->coupon_id && !$coupon)) { return; } $original = (int) ($price * 100); $couponAmount = match ((int) $coupon?->type) { 1 => (float) $coupon->value, 2 => $original * ((float) $coupon->value / 100), default => 0, }; $couponAmount = min($original, $couponAmount); $memberAmount = $original * ($percent / 100); // Capture only a breakdown that reconciles to this creation's XB values. if ($couponAmount < 0 || $percent < 0 || $percent > 100 || abs($total - $couponAmount - $memberAmount) > 0.000001) { return; } $savedTotal = (int) round((float) $order->fresh()->discount_amount); $couponCents = (int) round($couponAmount); if ($savedTotal < $couponCents) { return; } $breakdown = [ 'order_id' => $order->id, 'original_amount' => $original, 'member_amount' => $savedTotal - $couponCents, 'coupon_amount' => $couponCents, 'member_percent' => $percent, 'coupon_code' => $coupon?->code, ]; if ($coupon && Schema::hasColumn('fuc_order_discounts', 'coupon_type')) { $breakdown['coupon_type'] = (int) $coupon->type; } DB::table('fuc_order_discounts')->insertOrIgnore($breakdown); } }