DeliveryQuoteUtil.php 9.5 KB

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