DeliveryQuoteUtil.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. * 按配送方式满减规则判断是否免跑腿费(自定义计费与跑腿平台报价共用)。
  147. * 满扎数、满金额、距离在 freeKm 内同时满足时 sendCost 置 0,避免确认页显示免了、下单仍收起步价。
  148. * @param array $shConfig 配送方式配置,需含 reduceRules
  149. * @param float $sendCost 减免前跑腿费(元)
  150. * @param float $sendDistanceMeters 距离(米),内部会换算成公里再和 freeKm 比较
  151. * @param float $totalPrice 花材合计金额
  152. * @param float $totalNum 扎数
  153. * @return array ['sendCost' => 减免后金额]
  154. */
  155. public static function applyReduceRules($shConfig, $sendCost, $sendDistanceMeters, $totalPrice, $totalNum)
  156. {
  157. return self::discountSearch([
  158. 'shConfig' => $shConfig,
  159. 'sendCost' => $sendCost,
  160. 'sendDistance' => $sendDistanceMeters,
  161. 'freightType' => 0,
  162. 'totalPrice' => $totalPrice,
  163. 'totalNum' => $totalNum,
  164. ]);
  165. }
  166. // 查询是否符合跑腿的满减规则;sendDistance 单位为米
  167. private static function discountSearch($params)
  168. {
  169. $shConfig = $params['shConfig'] ?? [];
  170. $sendCost = $params['sendCost'] ?? 0;
  171. $sendDistance = $params['sendDistance'] ?? 0;
  172. $sendDistanceKm = bcdiv($sendDistance, 1000, 2);
  173. $freightType = $params['freightType'] ?? 0;
  174. //0 花束 1 花材
  175. $property = $params['property'] ?? 1;
  176. $totalPrice = $params['totalPrice'] ?? 0;
  177. $totalNum = $params['totalNum'] ?? 0;
  178. //免运费的情况 (配置本身设为包邮)
  179. if ($freightType == 1) {
  180. return ['sendCost' => 0];
  181. }
  182. // 遍历满减规则,判断是否符合免邮条件
  183. if (!empty($shConfig['reduceRules']) && is_array($shConfig['reduceRules'])) {
  184. foreach ($shConfig['reduceRules'] as $rule) {
  185. $meetNum = (float)($rule['meetNum'] ?? 0);
  186. $meetAmount = (float)($rule['meetAmount'] ?? 0);
  187. $freeKm = (float)($rule['freeKm'] ?? 0);
  188. // 校验规则:金额满 meetAmount 且 数量满 meetNum 且 距离在 freeKm 以内
  189. if ($totalPrice >= $meetAmount && $totalNum >= $meetNum && $sendDistanceKm <= $freeKm) {
  190. return ['sendCost' => 0];
  191. }
  192. }
  193. }
  194. return ['sendCost' => $sendCost];
  195. }
  196. /**
  197. * 计算商品总重量
  198. *
  199. * @param array $productList 商品列表
  200. * @return float 总重量(公斤)
  201. */
  202. private static function calculateTotalWeight($productList)
  203. {
  204. $weight = 0;
  205. // foreach ($productList as $itemData) {
  206. // $bigNum = $itemData['bigNum'] ?? 0;
  207. // $thisWeight = $itemData['weight'] ?? 0;
  208. // $currentWeight = bcmul($thisWeight, $bigNum, 2);
  209. // $weight = bcadd($currentWeight, $weight, 2);
  210. // }
  211. // TODO 先默认都是 1 公斤
  212. $weight = 1;
  213. return $weight;
  214. }
  215. /**
  216. * 构建订单数据
  217. *
  218. * @param array $params 参数数组
  219. * @param float $weight 总重量
  220. * @return array 订单数据
  221. */
  222. private static function buildOrderData($params, $weight)
  223. {
  224. $custom = $params['custom'];
  225. $orderInfo = $params['order'];
  226. return [
  227. 'orderSn' => $orderInfo['orderSn'],
  228. 'customName' => $custom->name,
  229. 'customMobile' => $custom->mobile,
  230. 'fullAddress' => $custom->fullAddress,
  231. 'floor' => $custom->floor,
  232. 'dist' => $custom->dist,
  233. 'lat' => $custom->lat,
  234. 'long' => $custom->long,
  235. 'address' => $custom->address,
  236. 'city' => $custom->city,
  237. 'weight' => $weight,
  238. 'remark' => $orderInfo['remark'] ?? '',
  239. 'prePrice' => $orderInfo['itemTotalAmount'] ?? 0,
  240. 'actPrice' => $orderInfo['itemTotalAmount'] ?? 0,
  241. 'goodsType' => $orderInfo['goodsType'],
  242. ];
  243. }
  244. /**
  245. * 应用免费配送规则
  246. *
  247. * @param float $sendCost 原始配送费用
  248. * @param int $sendDistance 配送距离(米)
  249. * @param int $shopId 店铺ID
  250. * @param int $productCount 商品数量
  251. * @param float $itemTotalAmount 商品总金额
  252. * @param int $ghsMainId 供货商mainId
  253. * @param string $orderSn 订单号
  254. * @param int $goodsType 商品类型:0花束 1花材
  255. * @return float 最终配送费用
  256. */
  257. private static function applyFreeDeliveryRules(
  258. $sendCost,
  259. $sendDistance,
  260. $shopId,
  261. $productCount,
  262. $itemTotalAmount,
  263. $ghsMainId,
  264. $orderSn,
  265. $goodsType
  266. ){
  267. // 获取店铺扩展信息(免费配送设置)
  268. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, null, 'id,hcFreeKm,hcMap,hsFreeKm,hsAddFee');
  269. if (empty($shopExt)) {
  270. return $sendCost;
  271. }
  272. if ($goodsType == 1) {//花材
  273. // 获取花材的免费配送设置
  274. $hcFreeKm = ($shopExt['hcFreeKm'] ?? 0) * 1000; // 转换为米
  275. $hcMapString = $shopExt['hcMap'] ?? '';
  276. $hcMap = [];
  277. if (!empty($hcMapString)) {
  278. $hcMap = json_decode($hcMapString, true);
  279. }
  280. // 判断是否免跑腿费
  281. if ($sendDistance > $hcFreeKm) {
  282. // 超过免费距离,检查是否满足其他免费条件
  283. if (count($hcMap) > 0) {
  284. foreach ($hcMap as $rule) {
  285. $ruleNum = $rule['num'] ?? 0;
  286. $rulePrice = $rule['price'] ?? 0;
  287. $ruleDistance = ($rule['distance'] ?? 0) * 1000;
  288. if ($productCount >= $ruleNum && $itemTotalAmount >= $rulePrice && $sendDistance <= $ruleDistance) {
  289. //noticeUtil::push("ghsMainId={$ghsMainId}, orderSn={$orderSn}, 免跑腿费,满足条件:" . json_encode($rule));
  290. return 0;
  291. }
  292. }
  293. }
  294. } else {
  295. // 在免费配送距离内
  296. return 0;
  297. }
  298. } else if ($goodsType == 0) {//花束
  299. // 获取花束的免费配送设置
  300. $hsFreeKm = ($shopExt['hsFreeKm'] ?? 0) * 1000; // 转换为米
  301. $hsAddFee = $shopExt['hsAddFee'] ?? 0;
  302. // 判断是否免跑腿费
  303. if ($sendDistance > $hsFreeKm) {
  304. $pass = bcsub($sendDistance, $hsFreeKm, 2);
  305. $km = bcdiv($pass,1000,2);
  306. //向上取整,不足1公里的按1公里算
  307. $km = ceil($km);
  308. return bcmul($km,$hsAddFee,2);
  309. } else {
  310. // 在免费配送距离内
  311. return 0;
  312. }
  313. } else {
  314. new \Exception('不支持的订单类型');
  315. }
  316. return $sendCost;
  317. }
  318. /**
  319. * 参数验证
  320. *
  321. * @param array $params 参数数组
  322. * @throws \Exception 当参数不合法时抛出异常
  323. */
  324. private static function validateParams($params)
  325. {
  326. $requiredFields = [
  327. 'productList',
  328. 'deliveryPlatform',
  329. 'ghsInfo',
  330. 'custom',
  331. 'order',
  332. 'mainId'
  333. ];
  334. foreach ($requiredFields as $field) {
  335. if (!isset($params[$field])) {
  336. throw new \Exception("缺少必要参数:{$field}");
  337. }
  338. }
  339. if (empty($params['productList']) || !is_array($params['productList'])) {
  340. throw new \Exception("商品列表不能为空");
  341. }
  342. if (empty($params['ghsInfo']['mainId']) || empty($params['ghsInfo']['shopId'])) {
  343. throw new \Exception("供货商信息不完整");
  344. }
  345. }
  346. }