6
0
Fork 0
jiqu-library-server/app/Services/ShippingService.php

73 lines
2.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services;
use App\Exceptions\BizException;
use App\Models\ShippingRule;
class ShippingService
{
/**
* 运费模板根据地址,重量, 商品金额 计算运费; 重量传g金额传分
*
* @param integer $weight
* @param integer $templateId
* @return void
*/
public function countShippingAmount(int $weight, int $totalAmount, int $templateId, int $zoneId)
{
$shipping_amount = 0;
//获取运费规则;
$rules = ShippingRule::with('zones')->where('template_id', $templateId)->get();
$canShipping = true;//是否支持寄送
//如果该模板下无运费规则,则直接包邮
if ($rules->count() > 0) {
//按包邮/计重
$rules = $rules->sortBy('type');
foreach ($rules as $rule) {
$canShipping = false;
$_ruleInfo = json_decode($rule->info, true);
if (in_array($zoneId, $rule->zones->pluck('id')->toArray())) {
$canShipping = true;
if ($rule->type == ShippingRule::TYPE_FREE) {
if ($totalAmount >= bcmul($_ruleInfo['threshold'], 100)) {//在包邮价格范围内
break;//跳出foreach循环, 直接包邮
}
} elseif ($rule->type == ShippingRule::TYPE_WEIGHT) {
$_firstWeight = (int) bcmul($_ruleInfo['first_weight'], 1000);
$_firstWamount = (int) bcmul($_ruleInfo['first_w_amount'], 100);
$_contiueWeight = (int) bcmul($_ruleInfo['continue_weight'], 1000);
$_contiueWamount = (int) bcmul($_ruleInfo['continue_w_amount'], 100);
if ($weight <= $_firstWeight) {
$shipping_amount = $_firstWamount;
break;
} else {//计算续重价格
$num = (int) bcdiv(($weight - $_firstWeight), $_contiueWeight);
$shipping_amount = (int) bcadd($_firstWamount, bcmul($num+1, $_contiueWamount));
break;
}
}
}
}
}
if (!$canShipping) {
throw new BizException('当前选择的地址有部分商品不支持配送');
}
return $this->returnAmount($shipping_amount);
}
/**
* 统一返回运费格式
*
* @param [type] $shipping_amount
* @return void
*/
protected function returnAmount($shipping_amount)
{
return $shipping_amount;
// return bcdiv($shipping_amount, 100, 2);
}
}