| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace Webkul\Shipping\Carriers;
- use Webkul\Checkout\Facades\Cart;
- use Webkul\Checkout\Models\CartShippingRate;
- use Webkul\Shipping\Models\ShippingZoneRate;
- class ZoneRate extends AbstractShipping
- {
- /**
- * Shipping method carrier code.
- *
- * @var string
- */
- protected $code = 'zonerate';
- /**
- * Shipping method code.
- *
- * @var string
- */
- protected $method = 'zonerate_zonerate';
- /**
- * Calculate rate for zone-based shipping.
- *
- * @return \Webkul\Checkout\Models\CartShippingRate|bool
- */
- public function calculate(): \Webkul\Checkout\Models\CartShippingRate|bool
- {
- if (! $this->isAvailable()) {
- return false;
- }
- $cart = Cart::getCart();
- if (! $cart) {
- return false;
- }
- $shippingAddress = $cart->shipping_address;
- if (! $shippingAddress) {
- return false;
- }
- $countryCode = $shippingAddress->country;
- // 检查该国家是否在允许列表中
- $allowedCountries = $this->getConfigData('allowed_countries');
- if ($allowedCountries) {
- $allowedList = array_filter(explode(',', $allowedCountries));
- if (! empty($allowedList) && ! in_array($countryCode, $allowedList)) {
- return false;
- }
- }
- $stateCode = $shippingAddress->state;
- // 查询匹配的费率:先精确匹配 country+state,再匹配 country+*
- $rate = ShippingZoneRate::active()
- ->byCountry($countryCode)
- ->byState($stateCode)
- ->byPrice($cart->base_grand_total)
- ->byRaw($countryCode, $stateCode)
- ->first();
- if (! $rate) {
- return false;
- }
- $cartShippingRate = new CartShippingRate;
- $cartShippingRate->carrier = $this->getCode();
- $cartShippingRate->carrier_title = $rate->carrier_title;
- $cartShippingRate->method = $this->getMethod();
- $cartShippingRate->method_title = $rate->delivery_type;
- $cartShippingRate->method_description = $rate->delivery_description;
- $cartShippingRate->price = core()->convertPrice($rate->price);
- $cartShippingRate->base_price = $rate->price;
- return $cartShippingRate;
- }
- /**
- * Get country options for the multiselect field in admin configuration.
- */
- public function getCountryOptions(): array
- {
- return core()->countries()->map(function ($country) {
- return [
- 'title' => $country->name,
- 'value' => $country->code,
- ];
- })->toArray();
- }
- }
|