ZoneRate.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Webkul\Shipping\Carriers;
  3. use Webkul\Checkout\Facades\Cart;
  4. use Webkul\Checkout\Models\CartShippingRate;
  5. use Webkul\Shipping\Models\ShippingZoneRate;
  6. class ZoneRate extends AbstractShipping
  7. {
  8. /**
  9. * Shipping method carrier code.
  10. *
  11. * @var string
  12. */
  13. protected $code = 'zonerate';
  14. /**
  15. * Shipping method code.
  16. *
  17. * @var string
  18. */
  19. protected $method = 'zonerate_zonerate';
  20. /**
  21. * Calculate rate for zone-based shipping.
  22. *
  23. * @return \Webkul\Checkout\Models\CartShippingRate|bool
  24. */
  25. public function calculate(): \Webkul\Checkout\Models\CartShippingRate|bool
  26. {
  27. if (! $this->isAvailable()) {
  28. return false;
  29. }
  30. $cart = Cart::getCart();
  31. if (! $cart) {
  32. return false;
  33. }
  34. $shippingAddress = $cart->shipping_address;
  35. if (! $shippingAddress) {
  36. return false;
  37. }
  38. $countryCode = $shippingAddress->country;
  39. // 检查该国家是否在允许列表中
  40. $allowedCountries = $this->getConfigData('allowed_countries');
  41. if ($allowedCountries) {
  42. $allowedList = array_filter(explode(',', $allowedCountries));
  43. if (! empty($allowedList) && ! in_array($countryCode, $allowedList)) {
  44. return false;
  45. }
  46. }
  47. $stateCode = $shippingAddress->state;
  48. // 查询匹配的费率:先精确匹配 country+state,再匹配 country+*
  49. $rate = ShippingZoneRate::active()
  50. ->byCountry($countryCode)
  51. ->byState($stateCode)
  52. ->byPrice($cart->base_grand_total)
  53. ->byRaw($countryCode, $stateCode)
  54. ->first();
  55. if (! $rate) {
  56. return false;
  57. }
  58. $cartShippingRate = new CartShippingRate;
  59. $cartShippingRate->carrier = $this->getCode();
  60. $cartShippingRate->carrier_title = $rate->carrier_title;
  61. $cartShippingRate->method = $this->getMethod();
  62. $cartShippingRate->method_title = $rate->delivery_type;
  63. $cartShippingRate->method_description = $rate->delivery_description;
  64. $cartShippingRate->price = core()->convertPrice($rate->price);
  65. $cartShippingRate->base_price = $rate->price;
  66. return $cartShippingRate;
  67. }
  68. /**
  69. * Get country options for the multiselect field in admin configuration.
  70. */
  71. public function getCountryOptions(): array
  72. {
  73. return core()->countries()->map(function ($country) {
  74. return [
  75. 'title' => $country->name,
  76. 'value' => $country->code,
  77. ];
  78. })->toArray();
  79. }
  80. }