DeliveryQuoteUtil.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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', 'didi'])) {
  76. $bracketContent = $params['deliveryBracketContent'] ?? '';
  77. if ($params['deliveryPlatform'] == 'didi') {
  78. $bracketContent = "滴滴 ({$bracketContent})";
  79. }
  80. $key = '';
  81. foreach ($deliveryList as $item) {
  82. if ($params['deliveryPlatform'] == 'huolala') {
  83. $key = 'vehicle_type';
  84. }
  85. if ($params['deliveryPlatform'] == 'fengniao') {
  86. $key = 'base_goods_id';
  87. }
  88. if ($params['deliveryPlatform'] == 'didi') {
  89. $key = 'name';
  90. }
  91. if ($item[$key] == $bracketContent) {
  92. $result = $item;
  93. }
  94. }
  95. if ($result === null) {
  96. throw new \Exception('没有找到对应的配送方式');
  97. }
  98. } else {
  99. $result = $deliveryList[0];
  100. }
  101. $sendCost = ($result['price'] ?? 0) / 100;
  102. $sendDistance = $result['distance'] ?? 0;
  103. // 11. 应用免费配送规则
  104. if(isset($params['order']['freightType']) && $params['order']['freightType'] == 0) { //用于处理及区分花束订单是否部分免跑腿费,还是完全收取跑腿费
  105. $finalSendCost= $sendCost;
  106. }else{
  107. $finalSendCost = self::applyFreeDeliveryRules(
  108. $sendCost,
  109. $sendDistance,
  110. $params['ghsInfo']['shopId'],
  111. $params['productCount'],
  112. $params['order']['itemTotalAmount'],
  113. $params['ghsInfo']['mainId'],
  114. $order['orderSn'],
  115. $order['goodsType']
  116. );
  117. }
  118. return [
  119. 'sendCost' => $finalSendCost,
  120. 'sendDistance' => $sendDistance,
  121. 'deliveryList' => $deliveryList,
  122. 'platformQuotes' => $platformQuotes,
  123. ];
  124. }
  125. /**
  126. * 计算商品总重量
  127. *
  128. * @param array $productList 商品列表
  129. * @return float 总重量(公斤)
  130. */
  131. private static function calculateTotalWeight($productList)
  132. {
  133. $weight = 0;
  134. // foreach ($productList as $itemData) {
  135. // $bigNum = $itemData['bigNum'] ?? 0;
  136. // $thisWeight = $itemData['weight'] ?? 0;
  137. // $currentWeight = bcmul($thisWeight, $bigNum, 2);
  138. // $weight = bcadd($currentWeight, $weight, 2);
  139. // }
  140. // TODO 先默认都是 1 公斤
  141. $weight = 1;
  142. return $weight;
  143. }
  144. /**
  145. * 构建订单数据
  146. *
  147. * @param array $params 参数数组
  148. * @param float $weight 总重量
  149. * @return array 订单数据
  150. */
  151. private static function buildOrderData($params, $weight)
  152. {
  153. $custom = $params['custom'];
  154. $orderInfo = $params['order'];
  155. return [
  156. 'orderSn' => $orderInfo['orderSn'],
  157. 'customName' => $custom->name,
  158. 'customMobile' => $custom->mobile,
  159. 'fullAddress' => $custom->fullAddress,
  160. 'floor' => $custom->floor,
  161. 'dist' => $custom->dist,
  162. 'lat' => $custom->lat,
  163. 'long' => $custom->long,
  164. 'address' => $custom->address,
  165. 'city' => $custom->city,
  166. 'weight' => $weight,
  167. 'remark' => $orderInfo['remark'] ?? '',
  168. 'prePrice' => $orderInfo['itemTotalAmount'] ?? 0,
  169. 'actPrice' => $orderInfo['itemTotalAmount'] ?? 0,
  170. 'goodsType' => $orderInfo['goodsType'],
  171. ];
  172. }
  173. /**
  174. * 应用免费配送规则
  175. *
  176. * @param float $sendCost 原始配送费用
  177. * @param int $sendDistance 配送距离(米)
  178. * @param int $shopId 店铺ID
  179. * @param int $productCount 商品数量
  180. * @param float $itemTotalAmount 商品总金额
  181. * @param int $ghsMainId 供货商mainId
  182. * @param string $orderSn 订单号
  183. * @param int $goodsType 商品类型:0花束 1花材
  184. * @return float 最终配送费用
  185. */
  186. private static function applyFreeDeliveryRules(
  187. $sendCost,
  188. $sendDistance,
  189. $shopId,
  190. $productCount,
  191. $itemTotalAmount,
  192. $ghsMainId,
  193. $orderSn,
  194. $goodsType
  195. ){
  196. // 获取店铺扩展信息(免费配送设置)
  197. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, null, 'id,hcFreeKm,hcMap,hsFreeKm,hsAddFee');
  198. if (empty($shopExt)) {
  199. return $sendCost;
  200. }
  201. if ($goodsType == 1) {//花材
  202. // 获取花材的免费配送设置
  203. $hcFreeKm = ($shopExt['hcFreeKm'] ?? 0) * 1000; // 转换为米
  204. $hcMapString = $shopExt['hcMap'] ?? '';
  205. $hcMap = [];
  206. if (!empty($hcMapString)) {
  207. $hcMap = json_decode($hcMapString, true);
  208. }
  209. // 判断是否免跑腿费
  210. if ($sendDistance > $hcFreeKm) {
  211. // 超过免费距离,检查是否满足其他免费条件
  212. if (count($hcMap) > 0) {
  213. foreach ($hcMap as $rule) {
  214. $ruleNum = $rule['num'] ?? 0;
  215. $rulePrice = $rule['price'] ?? 0;
  216. $ruleDistance = ($rule['distance'] ?? 0) * 1000;
  217. if ($productCount >= $ruleNum && $itemTotalAmount >= $rulePrice && $sendDistance <= $ruleDistance) {
  218. //noticeUtil::push("ghsMainId={$ghsMainId}, orderSn={$orderSn}, 免跑腿费,满足条件:" . json_encode($rule));
  219. return 0;
  220. }
  221. }
  222. }
  223. } else {
  224. // 在免费配送距离内
  225. return 0;
  226. }
  227. } else if ($goodsType == 0) {//花束
  228. // 获取花束的免费配送设置
  229. $hsFreeKm = ($shopExt['hsFreeKm'] ?? 0) * 1000; // 转换为米
  230. $hsAddFee = $shopExt['hsAddFee'] ?? 0;
  231. // 判断是否免跑腿费
  232. if ($sendDistance > $hsFreeKm) {
  233. $pass = bcsub($sendDistance, $hsFreeKm, 2);
  234. $km = bcdiv($pass,1000,2);
  235. //向上取整,不足1公里的按1公里算
  236. $km = ceil($km);
  237. return bcmul($km,$hsAddFee,2);
  238. } else {
  239. // 在免费配送距离内
  240. return 0;
  241. }
  242. } else {
  243. new \Exception('不支持的订单类型');
  244. }
  245. return $sendCost;
  246. }
  247. /**
  248. * 参数验证
  249. *
  250. * @param array $params 参数数组
  251. * @throws \Exception 当参数不合法时抛出异常
  252. */
  253. private static function validateParams($params)
  254. {
  255. $requiredFields = [
  256. 'productList',
  257. 'deliveryPlatform',
  258. 'ghsInfo',
  259. 'custom',
  260. 'order',
  261. 'mainId'
  262. ];
  263. foreach ($requiredFields as $field) {
  264. if (!isset($params[$field])) {
  265. throw new \Exception("缺少必要参数:{$field}");
  266. }
  267. }
  268. if (empty($params['productList']) || !is_array($params['productList'])) {
  269. throw new \Exception("商品列表不能为空");
  270. }
  271. if (empty($params['ghsInfo']['mainId']) || empty($params['ghsInfo']['shopId'])) {
  272. throw new \Exception("供货商信息不完整");
  273. }
  274. }
  275. }