DeliveryQuoteUtil.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. namespace common\components\delivery\util;
  3. use biz\shop\classes\ShopClass;
  4. use biz\shop\classes\ShopExtClass;
  5. use common\components\delivery\services\DispatchService;
  6. use common\components\noticeUtil;
  7. use Yii;
  8. /**
  9. * 配送报价工具类
  10. * 用于统一处理跑腿平台报价、免费配送规则等逻辑
  11. */
  12. class DeliveryQuoteUtil
  13. {
  14. /**
  15. * 获取配送报价(含免费配送规则计算)
  16. *
  17. * @param array $params 参数数组
  18. * - productList: 商品列表 [['bigNum' => 数量, 'weight' => 重量], ...]
  19. * - deliveryPlatform: 配送平台(shansong/huolala/fengniao等)
  20. * - ghsInfo: 供货商信息 ['mainId' => xxx, 'shopId' => xxx]
  21. * - custom: 客户信息对象(包含 name, mobile, fullAddress, lat, long 等)
  22. * - order: 订单基础信息 ['orderSn' => xxx, 'itemTotalAmount' => xxx, 'remark' => xxx]
  23. * - mainId: 当前操作者的 mainId
  24. * - productCount: 商品总数量(用于免费配送判断)
  25. *
  26. * @return array 返回数组
  27. * - sendCost: 配送费用(元)
  28. * - sendDistance: 配送距离(米)
  29. * - deliveryList: 可选配送方式列表
  30. * - platformQuotes: 原始平台报价数据
  31. *
  32. * @throws \Exception 当报价失败时抛出异常
  33. */
  34. public static function getDeliveryQuote($params)
  35. {
  36. // 1. 参数验证
  37. self::validateParams($params);
  38. // 2. 计算商品总重量
  39. $weight = self::calculateTotalWeight($params['productList']);
  40. // 3. 构建订单数据
  41. $order = self::buildOrderData($params, $weight);
  42. // 4. 获取供货商店铺信息
  43. $ghsShop = ShopClass::getById($params['ghsInfo']['shopId']);
  44. if (empty($ghsShop)) {
  45. throw new \Exception("供货商店铺信息不存在:shopId={$params['ghsInfo']['shopId']}");
  46. }
  47. // 5. 调用跑腿平台获取报价
  48. $orderTime = date('Y-m-d H:i:s');
  49. $ds = new DispatchService($params['ghsInfo']['mainId'], $params['deliveryPlatform']);
  50. $platformQuotes = $ds->getAllPlatformPrice($order, $ghsShop, $orderTime);
  51. // 6. 检查报价结果
  52. if (isset($platformQuotes['error'])) {
  53. $errorMsg = $platformQuotes['error'];
  54. Yii::error($errorMsg);
  55. noticeUtil::push("{$params['deliveryPlatform']}-跑腿平台估价接口获取费用与距离失败:mainId={$params['mainId']}");
  56. throw new \Exception($errorMsg);
  57. }
  58. // 7. 格式化平台报价
  59. $deliveryList = $ds->formatPlatformQuotesForDisplay($platformQuotes);
  60. // 8. 重试机制(如果第一次失败)
  61. if (is_array($deliveryList) && empty($deliveryList)) {
  62. sleep(2);
  63. $platformQuotes = $ds->getAllPlatformPrice($order, $ghsShop, $orderTime);
  64. $deliveryList = $ds->formatPlatformQuotesForDisplay($platformQuotes);
  65. }
  66. // 9. 检查是否有可用的配送方式
  67. if (is_array($deliveryList) && empty($deliveryList)) {
  68. $errorMsg = "ghsMainId={$params['ghsInfo']['mainId']}, orderSn={$order['orderSn']} 请求{$params['deliveryPlatform']}平台报价失败。";
  69. noticeUtil::push($errorMsg);
  70. Yii::error($errorMsg);
  71. throw new \Exception($errorMsg);
  72. }
  73. // 10. 获取报价结果
  74. $result = null;
  75. if (in_array($params['deliveryPlatform'], ['huolala', 'fengniao'])) {
  76. $bracketContent = $params['deliveryBracketContent'] ?? '';
  77. $key = '';
  78. foreach ($deliveryList as $item) {
  79. if ($params['deliveryPlatform'] == 'huolala') {
  80. $key = 'vehicle_type';
  81. }
  82. if ($params['deliveryPlatform'] == 'fengniao') {
  83. $key = 'base_goods_id';
  84. }
  85. if ($item[$key] == $bracketContent) {
  86. $result = $item;
  87. }
  88. }
  89. if ($result === null) {
  90. throw new \Exception('没有找到对应的配送方式');
  91. }
  92. } else {
  93. $result = $deliveryList[0];
  94. }
  95. $sendCost = ($result['price'] ?? 0) / 100;
  96. $sendDistance = $result['distance'] ?? 0;
  97. // 11. 应用免费配送规则
  98. if(isset($params['order']['freightType']) && $params['order']['freightType'] == 0) { //用于处理及区分花束订单是否部分免跑腿费,还是完全收取跑腿费
  99. $finalSendCost= $sendCost;
  100. }else{
  101. $finalSendCost = self::applyFreeDeliveryRules(
  102. $sendCost,
  103. $sendDistance,
  104. $params['ghsInfo']['shopId'],
  105. $params['productCount'],
  106. $params['order']['itemTotalAmount'],
  107. $params['ghsInfo']['mainId'],
  108. $order['orderSn'],
  109. $order['goodsType']
  110. );
  111. }
  112. return [
  113. 'sendCost' => $finalSendCost,
  114. 'sendDistance' => $sendDistance,
  115. 'deliveryList' => $deliveryList,
  116. 'platformQuotes' => $platformQuotes,
  117. ];
  118. }
  119. /**
  120. * 计算商品总重量
  121. *
  122. * @param array $productList 商品列表
  123. * @return float 总重量(公斤)
  124. */
  125. private static function calculateTotalWeight($productList)
  126. {
  127. $weight = 0;
  128. // foreach ($productList as $itemData) {
  129. // $bigNum = $itemData['bigNum'] ?? 0;
  130. // $thisWeight = $itemData['weight'] ?? 0;
  131. // $currentWeight = bcmul($thisWeight, $bigNum, 2);
  132. // $weight = bcadd($currentWeight, $weight, 2);
  133. // }
  134. // TODO 先默认都是 1 公斤
  135. $weight = 1;
  136. return $weight;
  137. }
  138. /**
  139. * 构建订单数据
  140. *
  141. * @param array $params 参数数组
  142. * @param float $weight 总重量
  143. * @return array 订单数据
  144. */
  145. private static function buildOrderData($params, $weight)
  146. {
  147. $custom = $params['custom'];
  148. $orderInfo = $params['order'];
  149. return [
  150. 'orderSn' => $orderInfo['orderSn'],
  151. 'customName' => $custom->name,
  152. 'customMobile' => $custom->mobile,
  153. 'fullAddress' => $custom->fullAddress,
  154. 'floor' => $custom->floor,
  155. 'dist' => $custom->dist,
  156. 'lat' => $custom->lat,
  157. 'long' => $custom->long,
  158. 'address' => $custom->address,
  159. 'city' => $custom->city,
  160. 'weight' => $weight,
  161. 'remark' => $orderInfo['remark'] ?? '',
  162. 'prePrice' => $orderInfo['itemTotalAmount'] ?? 0,
  163. 'actPrice' => $orderInfo['itemTotalAmount'] ?? 0,
  164. 'goodsType' => $orderInfo['goodsType'],
  165. ];
  166. }
  167. /**
  168. * 应用免费配送规则
  169. *
  170. * @param float $sendCost 原始配送费用
  171. * @param int $sendDistance 配送距离(米)
  172. * @param int $shopId 店铺ID
  173. * @param int $productCount 商品数量
  174. * @param float $itemTotalAmount 商品总金额
  175. * @param int $ghsMainId 供货商mainId
  176. * @param string $orderSn 订单号
  177. * @param int $goodsType 商品类型:0花束 1花材
  178. * @return float 最终配送费用
  179. */
  180. private static function applyFreeDeliveryRules(
  181. $sendCost,
  182. $sendDistance,
  183. $shopId,
  184. $productCount,
  185. $itemTotalAmount,
  186. $ghsMainId,
  187. $orderSn,
  188. $goodsType
  189. ){
  190. // 获取店铺扩展信息(免费配送设置)
  191. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, null, 'id,hcFreeKm,hcMap,hsFreeKm,hsAddFee');
  192. if (empty($shopExt)) {
  193. return $sendCost;
  194. }
  195. if ($goodsType == 1) {//花材
  196. // 获取花材的免费配送设置
  197. $hcFreeKm = ($shopExt['hcFreeKm'] ?? 0) * 1000; // 转换为米
  198. $hcMapString = $shopExt['hcMap'] ?? '';
  199. $hcMap = [];
  200. if (!empty($hcMapString)) {
  201. $hcMap = json_decode($hcMapString, true);
  202. }
  203. // 判断是否免跑腿费
  204. if ($sendDistance > $hcFreeKm) {
  205. // 超过免费距离,检查是否满足其他免费条件
  206. if (count($hcMap) > 0) {
  207. foreach ($hcMap as $rule) {
  208. $ruleNum = $rule['num'] ?? 0;
  209. $rulePrice = $rule['price'] ?? 0;
  210. $ruleDistance = ($rule['distance'] ?? 0) * 1000;
  211. if ($productCount >= $ruleNum && $itemTotalAmount >= $rulePrice && $sendDistance <= $ruleDistance) {
  212. //noticeUtil::push("ghsMainId={$ghsMainId}, orderSn={$orderSn}, 免跑腿费,满足条件:" . json_encode($rule));
  213. return 0;
  214. }
  215. }
  216. }
  217. } else {
  218. // 在免费配送距离内
  219. return 0;
  220. }
  221. } else if ($goodsType == 0) {//花束
  222. // 获取花束的免费配送设置
  223. $hsFreeKm = ($shopExt['hsFreeKm'] ?? 0) * 1000; // 转换为米
  224. $hsAddFee = $shopExt['hsAddFee'] ?? 0;
  225. // 判断是否免跑腿费
  226. if ($sendDistance > $hsFreeKm) {
  227. $pass = bcsub($sendDistance, $hsFreeKm, 2);
  228. $km = bcdiv($pass,1000,2);
  229. //向上取整,不足1公里的按1公里算
  230. $km = ceil($km);
  231. return bcmul($km,$hsAddFee,2);
  232. } else {
  233. // 在免费配送距离内
  234. return 0;
  235. }
  236. } else {
  237. new \Exception('不支持的订单类型');
  238. }
  239. return $sendCost;
  240. }
  241. /**
  242. * 参数验证
  243. *
  244. * @param array $params 参数数组
  245. * @throws \Exception 当参数不合法时抛出异常
  246. */
  247. private static function validateParams($params)
  248. {
  249. $requiredFields = [
  250. 'productList',
  251. 'deliveryPlatform',
  252. 'ghsInfo',
  253. 'custom',
  254. 'order',
  255. 'mainId'
  256. ];
  257. foreach ($requiredFields as $field) {
  258. if (!isset($params[$field])) {
  259. throw new \Exception("缺少必要参数:{$field}");
  260. }
  261. }
  262. if (empty($params['productList']) || !is_array($params['productList'])) {
  263. throw new \Exception("商品列表不能为空");
  264. }
  265. if (empty($params['ghsInfo']['mainId']) || empty($params['ghsInfo']['shopId'])) {
  266. throw new \Exception("供货商信息不完整");
  267. }
  268. }
  269. }