DeliveryQuoteUtil.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. if (empty($params['shConfig'])) {
  104. //旧的规则走这个
  105. // 11. 应用免费配送规则
  106. if (isset($params['order']['freightType']) && $params['order']['freightType'] == 0) { //用于处理及区分花束订单是否部分免跑腿费,还是完全收取跑腿费
  107. $finalSendCost = $sendCost;
  108. } else {
  109. $finalSendCost = self::applyFreeDeliveryRules(
  110. $sendCost,
  111. $sendDistance,
  112. $params['ghsInfo']['shopId'],
  113. $params['productCount'],
  114. $params['order']['itemTotalAmount'],
  115. $params['ghsInfo']['mainId'],
  116. $order['orderSn'],
  117. $order['goodsType']
  118. );
  119. }
  120. } else {
  121. //新免费规则走这里,欧阳写到这里有问题沟通 ssh 20260730
  122. $freightType = $params['order']['freightType'] ?? 0; //运费计算方式,0 按距离计算 1 免运费,包运费
  123. $property = $order['goodsType'] ?? 1;//订单是什么类型订单 0 花束订单 1 花材订单,多种商品,只要含一把花束,就是花束订单
  124. $totalPrice = $params['order']['itemTotalAmount'] ?? 0;
  125. $totalNum = $params['productCount'] ?? 0;
  126. $element = [
  127. 'shConfig' => $params['shConfig'],
  128. 'sendCost' => $sendCost,
  129. 'sendDistance' => $sendDistance,
  130. 'freightType' => $freightType,
  131. 'property' => $property,
  132. 'totalPrice' => $totalPrice,
  133. 'totalNum' => $totalNum,
  134. ];
  135. $discountRespond = self::discountSearch($element);
  136. $finalSendCost = $discountRespond['sendCost'] ?? 0;
  137. }
  138. return [
  139. 'sendCost' => $finalSendCost,
  140. 'sendDistance' => $sendDistance,
  141. 'deliveryList' => $deliveryList,
  142. 'platformQuotes' => $platformQuotes,
  143. ];
  144. }
  145. //查询是否符合跑腿的满减规则
  146. private static function discountSearch($params)
  147. {
  148. $shConfig = $params['shConfig'] ?? [];
  149. $sendCost = $params['sendCost'] ?? 0;
  150. $sendDistance = $params['sendDistance'] ?? 0;
  151. $freightType = $params['freightType'] ?? 0;
  152. $property = $params['property'] ?? 1;
  153. $totalPrice = $params['totalPrice'] ?? 0;
  154. $totalNum = $params['totalNum'] ?? 0;
  155. //免运费的情况 (配置本身设为包邮)
  156. if ($freightType == 1) {
  157. return ['sendCost' => 0];
  158. }
  159. // 遍历满减规则,判断是否符合免邮条件
  160. if (!empty($shConfig['reduceRules']) && is_array($shConfig['reduceRules'])) {
  161. foreach ($shConfig['reduceRules'] as $rule) {
  162. $meetNum = (float)($rule['meetNum'] ?? 0);
  163. $meetAmount = (float)($rule['meetAmount'] ?? 0);
  164. $freeKm = (float)($rule['freeKm'] ?? 0);
  165. // 校验规则:金额满 meetAmount 且 数量满 meetNum 且 距离在 freeKm 以内
  166. if ($totalPrice >= $meetAmount && $totalNum >= $meetNum && $sendDistance <= $freeKm) {
  167. return ['sendCost' => 0];
  168. }
  169. }
  170. }
  171. return ['sendCost' => $sendCost];
  172. }
  173. /**
  174. * 计算商品总重量
  175. *
  176. * @param array $productList 商品列表
  177. * @return float 总重量(公斤)
  178. */
  179. private static function calculateTotalWeight($productList)
  180. {
  181. $weight = 0;
  182. // foreach ($productList as $itemData) {
  183. // $bigNum = $itemData['bigNum'] ?? 0;
  184. // $thisWeight = $itemData['weight'] ?? 0;
  185. // $currentWeight = bcmul($thisWeight, $bigNum, 2);
  186. // $weight = bcadd($currentWeight, $weight, 2);
  187. // }
  188. // TODO 先默认都是 1 公斤
  189. $weight = 1;
  190. return $weight;
  191. }
  192. /**
  193. * 构建订单数据
  194. *
  195. * @param array $params 参数数组
  196. * @param float $weight 总重量
  197. * @return array 订单数据
  198. */
  199. private static function buildOrderData($params, $weight)
  200. {
  201. $custom = $params['custom'];
  202. $orderInfo = $params['order'];
  203. return [
  204. 'orderSn' => $orderInfo['orderSn'],
  205. 'customName' => $custom->name,
  206. 'customMobile' => $custom->mobile,
  207. 'fullAddress' => $custom->fullAddress,
  208. 'floor' => $custom->floor,
  209. 'dist' => $custom->dist,
  210. 'lat' => $custom->lat,
  211. 'long' => $custom->long,
  212. 'address' => $custom->address,
  213. 'city' => $custom->city,
  214. 'weight' => $weight,
  215. 'remark' => $orderInfo['remark'] ?? '',
  216. 'prePrice' => $orderInfo['itemTotalAmount'] ?? 0,
  217. 'actPrice' => $orderInfo['itemTotalAmount'] ?? 0,
  218. 'goodsType' => $orderInfo['goodsType'],
  219. ];
  220. }
  221. /**
  222. * 应用免费配送规则
  223. *
  224. * @param float $sendCost 原始配送费用
  225. * @param int $sendDistance 配送距离(米)
  226. * @param int $shopId 店铺ID
  227. * @param int $productCount 商品数量
  228. * @param float $itemTotalAmount 商品总金额
  229. * @param int $ghsMainId 供货商mainId
  230. * @param string $orderSn 订单号
  231. * @param int $goodsType 商品类型:0花束 1花材
  232. * @return float 最终配送费用
  233. */
  234. private static function applyFreeDeliveryRules(
  235. $sendCost,
  236. $sendDistance,
  237. $shopId,
  238. $productCount,
  239. $itemTotalAmount,
  240. $ghsMainId,
  241. $orderSn,
  242. $goodsType
  243. ){
  244. // 获取店铺扩展信息(免费配送设置)
  245. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, null, 'id,hcFreeKm,hcMap,hsFreeKm,hsAddFee');
  246. if (empty($shopExt)) {
  247. return $sendCost;
  248. }
  249. if ($goodsType == 1) {//花材
  250. // 获取花材的免费配送设置
  251. $hcFreeKm = ($shopExt['hcFreeKm'] ?? 0) * 1000; // 转换为米
  252. $hcMapString = $shopExt['hcMap'] ?? '';
  253. $hcMap = [];
  254. if (!empty($hcMapString)) {
  255. $hcMap = json_decode($hcMapString, true);
  256. }
  257. // 判断是否免跑腿费
  258. if ($sendDistance > $hcFreeKm) {
  259. // 超过免费距离,检查是否满足其他免费条件
  260. if (count($hcMap) > 0) {
  261. foreach ($hcMap as $rule) {
  262. $ruleNum = $rule['num'] ?? 0;
  263. $rulePrice = $rule['price'] ?? 0;
  264. $ruleDistance = ($rule['distance'] ?? 0) * 1000;
  265. if ($productCount >= $ruleNum && $itemTotalAmount >= $rulePrice && $sendDistance <= $ruleDistance) {
  266. //noticeUtil::push("ghsMainId={$ghsMainId}, orderSn={$orderSn}, 免跑腿费,满足条件:" . json_encode($rule));
  267. return 0;
  268. }
  269. }
  270. }
  271. } else {
  272. // 在免费配送距离内
  273. return 0;
  274. }
  275. } else if ($goodsType == 0) {//花束
  276. // 获取花束的免费配送设置
  277. $hsFreeKm = ($shopExt['hsFreeKm'] ?? 0) * 1000; // 转换为米
  278. $hsAddFee = $shopExt['hsAddFee'] ?? 0;
  279. // 判断是否免跑腿费
  280. if ($sendDistance > $hsFreeKm) {
  281. $pass = bcsub($sendDistance, $hsFreeKm, 2);
  282. $km = bcdiv($pass,1000,2);
  283. //向上取整,不足1公里的按1公里算
  284. $km = ceil($km);
  285. return bcmul($km,$hsAddFee,2);
  286. } else {
  287. // 在免费配送距离内
  288. return 0;
  289. }
  290. } else {
  291. new \Exception('不支持的订单类型');
  292. }
  293. return $sendCost;
  294. }
  295. /**
  296. * 参数验证
  297. *
  298. * @param array $params 参数数组
  299. * @throws \Exception 当参数不合法时抛出异常
  300. */
  301. private static function validateParams($params)
  302. {
  303. $requiredFields = [
  304. 'productList',
  305. 'deliveryPlatform',
  306. 'ghsInfo',
  307. 'custom',
  308. 'order',
  309. 'mainId'
  310. ];
  311. foreach ($requiredFields as $field) {
  312. if (!isset($params[$field])) {
  313. throw new \Exception("缺少必要参数:{$field}");
  314. }
  315. }
  316. if (empty($params['productList']) || !is_array($params['productList'])) {
  317. throw new \Exception("商品列表不能为空");
  318. }
  319. if (empty($params['ghsInfo']['mainId']) || empty($params['ghsInfo']['shopId'])) {
  320. throw new \Exception("供货商信息不完整");
  321. }
  322. }
  323. }