DispatchService.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. <?php
  2. namespace common\components\delivery\services;
  3. use biz\shop\classes\ShopClass;
  4. use bizGhs\express\classes\DeliveryAuthTokenClass;
  5. use bizGhs\express\classes\GhsDeliveryOrderClass;
  6. use bizGhs\order\classes\OrderClass;
  7. use bizGhs\order\classes\OrderItemClass;
  8. use bizHd\express\classes\HdDeliveryOrderClass;
  9. use common\components\delivery\helpers\HttpClient;
  10. use common\components\delivery\services\adapter\{DadaAdapter,
  11. DidiAdapter,
  12. Functions,
  13. ShansongAdapter,
  14. HuolalaAdapter,
  15. FengniaoAdapter,
  16. ShunfengAdapter}; // MeituanAdapter, UUAdapter,
  17. use common\components\util;
  18. use Yii;
  19. /**
  20. * 聚合调度逻辑(平台选择/优先级)
  21. * Class DispatchService
  22. * @package App\Services
  23. */
  24. class DispatchService
  25. {
  26. protected $adapters;
  27. protected $platformName = '';
  28. public function __construct($mainId, $platform='')
  29. {
  30. if ($platform == '') {
  31. $authPlatforms = DeliveryAuthTokenClass::getAllByCondition(['mainId'=>$mainId]);
  32. foreach($authPlatforms as $pt) {
  33. switch ($pt['platform']) {
  34. case 'shansong':
  35. $this->adapters['shansong'] = new ShansongAdapter($pt['accessToken'], $pt['shopId']);
  36. break;
  37. case 'huolala':
  38. $this->adapters['huolala'] = new HuolalaAdapter($pt['accessToken']);
  39. break;
  40. case 'fengniao':
  41. $adapter = new FengniaoAdapter($pt['accessToken']);
  42. // 动态设置商户ID与门店ID
  43. $adapter->setMerchantId($pt['merchantId']);
  44. $adapter->setShopId($pt['shopId']);
  45. $this->adapters['fengniao'] = $adapter;
  46. break;
  47. case 'shunfeng':
  48. $this->adapters['shunfeng'] = new ShunfengAdapter($pt['accessToken'], $pt['shopId']);
  49. break;
  50. case 'dada':
  51. $this->adapters['dada'] = new DadaAdapter($pt['accessToken']);
  52. $this->adapters['dada']->setShopNo($pt['shopId']);
  53. $this->adapters['dada']->setSourceId($pt['merchantId']); // 用 merchanId 来保存 sourceId
  54. break;
  55. case 'didi':
  56. $this->adapters['didi'] = new DidiAdapter($pt['accessToken'], $pt['mainId']);
  57. break;
  58. }
  59. //检测 token 是否即将过期
  60. $tokenExpireTime = $pt['expiresAt'];
  61. if ($tokenExpireTime < time() + 86400 * 5) {
  62. Yii::info('刷新 token: ' . $pt['platform'] . ',refreshToken: ' . $pt['refreshToken'] . ',merchantId: ' . $pt['merchantId']);
  63. $this->refreshToken($pt['platform'], $pt['refreshToken'], ['merchantId' => $pt['merchantId']]);
  64. }
  65. }
  66. } else {
  67. $authPlatform = DeliveryAuthTokenClass::getByCondition(['mainId'=>$mainId, 'platform'=>$platform]);
  68. switch ($platform) {
  69. case 'shansong':
  70. $this->adapters['shansong'] = new ShansongAdapter($authPlatform['accessToken'], $authPlatform['shopId']);
  71. break;
  72. case 'huolala':
  73. $this->adapters['huolala'] = new HuolalaAdapter($authPlatform['accessToken']);
  74. break;
  75. case 'fengniao':
  76. //$this->adapters['fengniao'] = new FengniaoAdapter($authPlatform['accessToken']);
  77. $adapter = new FengniaoAdapter($authPlatform['accessToken']);
  78. // 动态设置商户ID与门店ID
  79. $adapter->setMerchantId($authPlatform['merchantId']);
  80. $adapter->setShopId($authPlatform['shopId']);
  81. $this->adapters['fengniao'] = $adapter;
  82. break;
  83. case 'shunfeng':
  84. $this->adapters['shunfeng'] = new ShunfengAdapter($authPlatform['accessToken'], $authPlatform['shopId']);
  85. break;
  86. case 'dada':
  87. $this->adapters['dada'] = new DadaAdapter($authPlatform['accessToken']);
  88. $this->adapters['dada']->setShopNo($authPlatform['shopId']);
  89. $this->adapters['dada']->setSourceId($authPlatform['merchantId']); // 用 merchanId 来保存 sourceId
  90. break;
  91. case 'didi':
  92. $this->adapters['didi'] = new DidiAdapter($authPlatform['accessToken'], $authPlatform['mainId']);
  93. break;
  94. }
  95. $this->platformName = $platform;
  96. if($authPlatform['expiresAt'] < time() + 86400 * 5) {
  97. Yii::info('刷新 token: ' . $platform . ',refreshToken: ' . $authPlatform['refreshToken'] . ',merchantId: ' . $authPlatform['merchantId']);
  98. $this->refreshToken($platform, $authPlatform['refreshToken'], ['merchantId' => $authPlatform['merchantId']]);
  99. }
  100. }
  101. }
  102. /**
  103. * @param $order
  104. * @param string $orderType 订单类型:xhOrder 或 xhGhsOrder
  105. * @param $shopId
  106. * @param $params
  107. * @return mixed
  108. */
  109. public function createOrder($order, $orderType, $shopId, $params)
  110. {
  111. $order = $order->toArray();
  112. if(!in_array($orderType, ['xhOrder', 'xhGhsOrder'])){
  113. util::fail('订单类型错误');
  114. }
  115. $shop = ShopClass::getById($shopId, false, 'id,merchantName,shopName,fullAddress,lat,long,city,dist,floor,mobile,merchantName');
  116. $adapter = $this->getAdapter();
  117. $orderData = $adapter->formatOrderData($order, $orderType, $shop, $params);
  118. return $adapter->createOrder($orderData);
  119. }
  120. /**
  121. *
  122. */
  123. public function addTip($data)
  124. {
  125. $adapter = $this->getAdapter();
  126. return $adapter->addTip($data);
  127. }
  128. /**
  129. * @param $orderId 平台订单号
  130. * @param string $thirdOrderNo xhGhsOrder.orderSn
  131. */
  132. public function selectOrder($orderId, $thirdOrderNo='')
  133. {
  134. $adapter = $this->getAdapter();
  135. if ($adapter instanceof ShansongAdapter) {
  136. $deliveryOrder = $this->getDeliveryOrder($orderId, 'shansong');
  137. return $adapter->selectOrder($deliveryOrder['orderId'], $thirdOrderNo);
  138. }
  139. if ($adapter instanceof HuolalaAdapter) {
  140. $deliveryOrder = $this->getDeliveryOrder($orderId, 'huolala');
  141. return $adapter->selectOrder($deliveryOrder['orderId']);
  142. }
  143. if ($adapter instanceof FengniaoAdapter) {
  144. $deliveryOrder = $this->getDeliveryOrder($orderId, 'fengniao');
  145. //order_id 和 partner_order_code 必填一个
  146. return $adapter->selectOrder(['order_id'=>$deliveryOrder['orderId']]);
  147. }
  148. if ($adapter instanceof ShunfengAdapter) {
  149. $deliveryOrder = $this->getDeliveryOrder($orderId, 'shunfeng');
  150. return $adapter->selectOrder($deliveryOrder['orderId']);
  151. }
  152. if ($adapter instanceof DadaAdapter) {
  153. $ghsOrder = OrderClass::getById($orderId, false, 'id,orderSn');
  154. return $adapter->selectOrder($ghsOrder['orderSn']);
  155. }
  156. if ($adapter instanceof DidiAdapter) {
  157. $deliveryOrder = $this->getDeliveryOrder($orderId, 'didi', 'id,orderId,createdAt');
  158. $timeStamp = strtoTime($deliveryOrder['createdAt']);
  159. return $adapter->selectOrder($deliveryOrder['orderId'], $thirdOrderNo, $timeStamp);
  160. }
  161. return $adapter->selectOrder($orderId);
  162. }
  163. /**
  164. * 根据订单号查找配送订单
  165. *
  166. * @param string $orderId
  167. * @return object|null
  168. */
  169. private function getDeliveryOrder($orderId, $deliveryId, $fields=null)
  170. {
  171. $fields = $fields ?? 'id,orderId';
  172. // 查找批发配送订单
  173. $deliveryOrder = GhsDeliveryOrderClass::getByCondition([
  174. 'deliveryId' => $deliveryId,
  175. 'ghsOrderId' => $orderId,
  176. 'orderStatus' => ['not in', [-1, -2]],
  177. ], false, null, $fields);
  178. if ($deliveryOrder) {
  179. return $deliveryOrder;
  180. }
  181. // 查找零售配送订单
  182. $deliveryOrder = HdDeliveryOrderClass::getByCondition([
  183. 'deliveryId' => $deliveryId,
  184. 'hdOrderId' => $orderId,
  185. 'orderStatus' => ['not in', [-1, -2]],
  186. ], false, null, $fields);
  187. if ($deliveryOrder) {
  188. return $deliveryOrder;
  189. }
  190. util::fail('未找到对应的配送订单: ' . $orderId);
  191. }
  192. public function cancelOrder($orderId, $reason)
  193. {
  194. $adapter = $this->getAdapter();
  195. return $adapter->cancelOrder($orderId, $reason);
  196. }
  197. public function getCancelReasonList($orderId)
  198. {
  199. $adapter = $this->getAdapter();
  200. return $adapter->getCancelReasonList($orderId);
  201. }
  202. public function getAdapter()
  203. {
  204. return $this->adapters[$this->platformName];
  205. }
  206. /**
  207. * 获取所有平台的最佳报价(使用 Guzzle 并发请求)
  208. *
  209. * 流程说明:
  210. * 1. 同步准备各平台的前置数据(如城市信息、订单商品等)
  211. * 2. 使用 Guzzle Pool 并发发送各平台的报价请求(5秒超时)
  212. * 3. 某个平台失败/超时不影响其他平台,继续等待结果
  213. *
  214. * @param array $order 订单信息
  215. * @param array $shop 店铺信息
  216. * @return array 返回所有平台的报价结果
  217. */
  218. public function getAllPlatformPrice($order, $shop, $orderTime)
  219. {
  220. // 第一步:准备前置数据(同步进行,因为某些平台需要这些数据)
  221. $preparedData = $this->preparePlatformData($order, $shop, $orderTime);
  222. if (empty($preparedData)) {
  223. return ['error' => '所有平台数据准备失败'];
  224. }
  225. // 第二步:并发调用各平台的报价接口
  226. $results = $this->concurrentGetPrices($preparedData, $orderTime);
  227. if (empty($results['success']) && empty($results['failed'])) {
  228. return ['error' => '没有可用的物流平台'];
  229. }
  230. // 格式化返回结果
  231. return [
  232. 'quotes' => $results['success'] ?? [],
  233. 'failed' => $results['failed'] ?? [],
  234. ];
  235. }
  236. /**
  237. * 为各平台准备订单数据(前置数据同步获取)
  238. *
  239. * @param array $order 订单信息
  240. * @param array $shop 店铺信息
  241. * @return array 各平台的订单数据
  242. */
  243. private function preparePlatformData($order, $shop, $orderTime)
  244. {
  245. $preparedData = [];
  246. // 准备 Huolala 数据
  247. if (isset($this->adapters['huolala'])) {
  248. try {
  249. $preparedData['huolala'] = $this->prepareHuolalaData($order, $shop);
  250. } catch (\Exception $e) {
  251. Yii::warning("Huolala 数据准备失败: {$e->getMessage()}");
  252. }
  253. }
  254. // 准备 Fengniao 数据
  255. if (isset($this->adapters['fengniao'])) {
  256. try {
  257. /** @var FengniaoAdapter $fengniaoAdapter */
  258. $fengniaoAdapter = $this->adapters['fengniao'];
  259. $platformShopId = $fengniaoAdapter->getShopId();
  260. $preparedData['fengniao'] = $this->prepareFengniaoData($order, $shop, $platformShopId);
  261. } catch (\Exception $e) {
  262. Yii::warning("Fengniao 数据准备失败: {$e->getMessage()}");
  263. }
  264. }
  265. // 准备 Shansong 数据
  266. if (isset($this->adapters['shansong'])) {
  267. try {
  268. $preparedData['shansong'] = $this->prepareShansongData($order, $shop, $orderTime);
  269. } catch (\Exception $e) {
  270. Yii::warning("Shansong 数据准备失败: {$e->getMessage()}");
  271. }
  272. }
  273. // 准备顺丰订单数据
  274. if (isset($this->adapters['shunfeng'])) {
  275. try {
  276. //$customSettings = $this->adapters['shunfeng']->getCustomSettings();
  277. $customSettings = [];//自定义用户设置:默认不专人直送
  278. $preparedData['shunfeng'] = $this->prepareShunfengData($order, $shop, $customSettings);
  279. //添加专人直送的订单数据
  280. $customSettings = ['isPersonDirect' => 1];//自定义用户设置:专人直送
  281. $preparedData['shunfeng_1v1'] = $this->prepareShunfengData($order, $shop, $customSettings);
  282. } catch (\Exception $e) {
  283. Yii::warning("Shunfeng 数据准备失败: {$e->getMessage()}");
  284. }
  285. }
  286. // 准备达达订单数据
  287. if (isset($this->adapters['dada'])) {
  288. try {
  289. $dadaAdapter = $this->adapters['dada'];
  290. $shopNo = $dadaAdapter->getShopNo();
  291. $preparedData['dada'] = $this->prepareDadaData($order, $shop, $shopNo);
  292. } catch (\Exception $e) {
  293. Yii::warning("Dada 数据准备失败: {$e->getMessage()}");
  294. }
  295. }
  296. // 准备滴滴订单数据
  297. if (isset($this->adapters['didi'])) {
  298. try {
  299. $preparedData['didi'] = $this->prepareDidiData($order, $shop);
  300. } catch (\Exception $e) {
  301. Yii::warning("Didi 数据准备失败: {$e->getMessage()}");
  302. }
  303. }
  304. return $preparedData;
  305. }
  306. /**
  307. * 准备货拉拉订单数据
  308. */
  309. private function prepareHuolalaData($order, $shop)
  310. {
  311. $formatCity = rtrim($order['city'], '市');
  312. $cities = include Yii::getAlias('@common/components/delivery/platform/huolala/cities.php');
  313. if (!isset($cities[$formatCity])) {
  314. throw new \Exception('城市编码表中没有找到城市: ' . $formatCity);
  315. }
  316. $cityId = $cities[$formatCity]['city_id'];
  317. $cityVehicleList = $this->adapters['huolala']->getCityVehicleList($cityId); // 产生外部请求
  318. $cityInfoRevision = $cityVehicleList['city_info_revision']; // 城市版本号
  319. $vehicleList = $cityVehicleList['vehicle_list']; // 所有车型列表
  320. if (empty($vehicleList)) {
  321. throw new \Exception('没有找到可选车型');
  322. }
  323. // 解析额外需求
  324. $specReqItem = $cityVehicleList['spec_req_item'] ?? [];
  325. $specReq = [];
  326. foreach ($specReqItem as $item) {
  327. $specReq[] = $item['type'] ?? null;
  328. }
  329. $specReq = array_filter($specReq);
  330. // 构建所有车型数据
  331. $vehicleTypeList = [];
  332. foreach ($vehicleList as $vehicle) {
  333. if(!in_array($vehicle['vehicle_name'], ['跑腿', '小面', '微面'])){ // && !$this->adapters['huolala']->getIsSandbox()
  334. continue;
  335. }
  336. $vehicleStd = [];
  337. $vehicleStd[] = count($vehicle['vehicle_std_item']) > 0 ? $vehicle['vehicle_std_item'][0]['name'] : '';
  338. $vehicleTypeList[$vehicle['order_vehicle_id']] = [
  339. 'order_vehicle_id' => $vehicle['order_vehicle_id'],
  340. 'city_info_revision' => $cityInfoRevision,
  341. 'order_time' => time() + 600,
  342. 'addr_info' => [
  343. [
  344. 'name' => $shop['merchantName'],
  345. 'addr' => $shop['province'] . $shop['city'] . $shop['dist'] . $shop['address'],
  346. 'city_id' => $cityId,
  347. 'city_name' => $shop['city'],
  348. 'district_name' => $shop['dist'],
  349. 'house_number' => $shop['floor'],
  350. 'contacts_name' => $shop['mobile'],
  351. 'contacts_phone_no' => $shop['mobile'],
  352. 'lat_lon' => ['lat' => (float)$shop['lat'], 'lon' => (float)$shop['long']],
  353. ],
  354. [
  355. 'name' => $order['customName'],
  356. 'addr' => $order['fullAddress'],
  357. 'city_id' => $cityId,
  358. 'city_name' => $order['city'],
  359. 'district_name' => $order['dist'],
  360. 'house_number' => $order['floor'],
  361. 'contacts_name' => $order['customName'],
  362. 'contacts_phone_no' => Functions::getMobile($order),
  363. 'lat_lon' => ['lat' => (float)$order['lat'], 'lon' => (float)$order['long']],
  364. ]
  365. ],
  366. 'vehicle_std' => $vehicleStd,
  367. 'spec_req' => array_values($specReq),
  368. 'coupon_id' => 123456, // TODO ??? 添加自动获取 coupon_id
  369. 'invoice_type' => 1,
  370. 'order_service_type' => 1,
  371. '_meta' => [
  372. 'vehicle_type' => $vehicle['vehicle_name'],
  373. 'city_info_revision' => $cityInfoRevision,
  374. ]
  375. ];
  376. }
  377. return [
  378. 'platform' => 'huolala',
  379. 'city_id' => $cityId,
  380. 'vehicle_type_list' => $vehicleTypeList,
  381. ];
  382. }
  383. /**
  384. * 准备蜂鸟订单数据
  385. */
  386. private function prepareFengniaoData($order, $shop, $platformShopId)
  387. {
  388. // $this->adapters['fengniao']->setMerchantId(14594092); // adapter 创建时已经设置了
  389. $goodsItemList = [];
  390. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num');
  391. foreach ($itemInfos as $item) {
  392. $goodsItemList[] = [
  393. 'item_actual_amount_cent' => (int)($item['unitPrice'] * 100 * $item['num']),
  394. 'item_amount_cent' => (int)($item['unitPrice'] * 100),
  395. 'item_id' => $item['id'],
  396. 'item_name' => $item['name'],
  397. 'item_quantity' => $item['num'],
  398. ];
  399. }
  400. return [
  401. 'platform' => 'fengniao',
  402. 'partner_order_code' => $order['orderSn'],
  403. 'receiver_primary_phone' => Functions::getMobile($order),
  404. 'receiver_name' => $order['customName'],
  405. 'receiver_latitude' => (float)$order['lat'],
  406. 'receiver_longitude' => (float)$order['long'],
  407. 'receiver_address' => $order['fullAddress'],
  408. 'position_source' => 3,
  409. 'goods_count' => count($goodsItemList),
  410. 'goods_weight' => (float)$order['weight'],
  411. 'goods_total_amount_cent' => (int)($order['actPrice'] * 100),
  412. 'goods_actual_amount_cent' => (int)($order['prePrice'] * 100),
  413. 'goods_item_list' => $goodsItemList,
  414. 'order_type' => 1,
  415. 'chain_store_id' => $platformShopId, // 蜂鸟平台 shopId
  416. 'order_remark' => $order['remark'] ?? '',
  417. ];
  418. }
  419. /**
  420. * 准备闪送订单数据
  421. */
  422. private function prepareShansongData($order, $shop, $orderTime)
  423. {
  424. $data = [
  425. 'platform' => 'shansong',
  426. 'cityName' => $shop['city'],
  427. 'sender' => [
  428. 'fromAddress' => $shop['address'],
  429. 'fromAddressDetail' => $shop['floor'],
  430. 'fromSenderName' => $shop['shopName'] == '首店' ? $shop['merchantName'] : $shop['merchantName'].'-'.$shop['shopName'],
  431. 'fromMobile' => $shop['mobile'],
  432. 'fromLatitude' => (string)$shop['lat'],
  433. 'fromLongitude' => (string)$shop['long'],
  434. ],
  435. 'receiverList' => [
  436. [
  437. 'orderNo' => $order['orderSn'],
  438. 'toAddress' => $order['address'],
  439. 'toAddressDetail' => $order['floor'],
  440. 'toReceiverName' => $order['customName'],
  441. 'toMobile' => Functions::getMobile($order),
  442. 'toLatitude' => (string)$order['lat'],
  443. 'toLongitude' => (string)$order['long'],
  444. 'goodType' => 7, //鲜花
  445. 'weight' => (int)round($order['weight']),
  446. 'remarks' => $order['remark'] ?? '',
  447. ]
  448. ],
  449. 'appointType' => 0, //预约类型: 0立即单,1预约单
  450. 'travelWay' => 0,
  451. 'deliveryType' => 1,
  452. //补充额外的订单数据
  453. 'sendNum' => $order['sendNum'],
  454. ];
  455. $timestamp = strtotime($orderTime);
  456. $currentTime = time() + 3600;
  457. if($timestamp > $currentTime){
  458. $data['appointType'] = 1; // 修改预约类型
  459. $data['appointmentDate'] = $orderTime; // 预约时间, yyyy-MM-dd HH:mm格式(例如:2020-02-02 22:00),指的是预约取件时间,只支持一个小时以后两天以内
  460. // 'expectStartTime' 期望送达时间起始时间 -- 毫秒级时间戳。期望送达时间为时间点时,无需传本参数;期望送达时间为时间段时,期望送达时间为expectStartTime至expectEndTime
  461. // 'expectEndTime' 期望送达时间终止时间 -- 毫秒级时间戳。期望送达时间为时间点时,只需传本参数;期望送达时间为时间段时,期望送达时间为expectStartTime至expectEndTime
  462. $data['receiverList'][0]['expectStartTime'] = ($timestamp + 900) * 1000;
  463. $data['receiverList'][0]['expectEndTime'] = ($timestamp + 1800) * 1000;
  464. }
  465. return $data;
  466. }
  467. /**
  468. * 准备顺丰订单数据
  469. */
  470. private function prepareShunfengData($order, $shop, $customSettings)
  471. {
  472. // 获取订单商品信息
  473. // $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num, unitWeight');
  474. // 计算商品总重量(单位:克)
  475. // $totalWeight = 0;
  476. // foreach ($itemInfos as $item) {
  477. // $totalWeight += (int)($item['unitWeight'] * $item['num']) * 1000;
  478. // }
  479. // 如果没有商品重量,使用订单重量
  480. // if ($totalWeight == 0 && isset($order['weight'])) {
  481. // $totalWeight = (int)$order['weight'] * 1000;
  482. // }
  483. // 默认重量为1000克(1公斤)
  484. // if ($totalWeight == 0) {
  485. // $totalWeight = 1000;
  486. // }
  487. return [
  488. 'platform' => 'shunfeng',
  489. 'user_lng' => (string)$order['long'], // 用户地址经度
  490. 'user_lat' => (string)$order['lat'], // 用户地址纬度
  491. 'user_address' => $order['fullAddress'], // 用户详细地址
  492. 'weight' => $order['weight'] * 1000, // 物品重量(单位:克)
  493. 'product_type' => 4, // 物品类型(4:鲜花绿植)
  494. 'push_time' => time(), // 推单时间(秒级时间戳)
  495. 'shop' => [ // 发货店铺信息
  496. 'shop_name' => $shop['merchantName'], // 店铺名称
  497. 'shop_address' => $shop['address'], // 店铺地址
  498. 'shop_lng' => (string)$shop['long'], // 店铺经度
  499. 'shop_lat' => (string)$shop['lat'], // 店铺纬度
  500. 'shop_phone' => $shop['mobile'], // 店铺联系电话
  501. ],
  502. //-------------------------- 非必填 -------------------------------
  503. 'city_name' => $order['city'], // 发单城市
  504. //'order_source' => '6', // 订单接入来源(6:京东秒送,可自定义)
  505. 'source_origin_order_id' => $order['orderSn'], // 商流订单号
  506. 'total_price' => (int)($order['actPrice'] * 100), // 用户订单总金额(单位:分)
  507. 'is_appoint' => 0, // 是否预约单(0:非预约单)
  508. 'appoint_type' => 0, // TODO 预约单类型(0:立即单)
  509. 'expect_time' => 0, // TODO 用户期望送达时间
  510. //'expect_pickup_time' => 0, // TODO 用户期望上门时间 -- appoint_type=2时需必传,秒级时间戳
  511. 'shop_expect_time' => 0, // TODO 商家期望送达时间 -- 格式为:{timestamp},
  512. 'lbs_type' => 2, // 坐标类型(2:高德坐标)
  513. 'is_insured' => 0, // 是否保价(0:非保价)
  514. 'is_person_direct' => $customSettings['isPersonDirect'] ?? 0, // 是否专人直送(0:否 1:是)
  515. 'vehicle' => 0, // 配送交通工具(0:否)
  516. //'four_wheeler_type' => 0, // 车型 -- 只有vehicle = 2,⻋型字段才有效。
  517. //'declared_value' => 0, // 保价金额(单位:分)
  518. //'gratuity_fee' => 0, // 订单小费(单位:分)
  519. 'rider_pick_method' => 1, // 物流流向(1:从门店取件送至用户)
  520. 'return_flag' => 511, // 返回字段控制标志位(511:全部返回)
  521. 'multi_pickup_info' => [], // 多点取货信息(暂不使用)
  522. ];
  523. }
  524. /**
  525. * 准备达达订单数据
  526. */
  527. private function prepareDadaData($order, $shop, $shopNo)
  528. {
  529. $productList = [];
  530. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num, bigNum, smallNum, xhUnitName');
  531. foreach ($itemInfos as $item) {
  532. $productList[] = [
  533. 'sku_name' => $item['name'],
  534. 'src_product_no' => (string)$item['id'],
  535. 'count' => (float)$item['num'],
  536. 'unit' => $item['xhUnitName'],
  537. ];
  538. }
  539. // 回调地址
  540. $callbackUrl = Yii::$app->params['ghsHost'] . '/delivery/dada-callback';
  541. return [
  542. 'platform' => 'dada',
  543. 'shop_no' => $shopNo,
  544. 'origin_id' => $order['orderSn'],
  545. 'cargo_price' => (float)$order['actPrice'],
  546. 'is_prepay' => 0, // 是否需要垫付 1:是 0:否 (垫付订单金额,非运费)
  547. 'receiver_name' => $order['customName'],
  548. 'receiver_address' => $order['fullAddress'],
  549. 'receiver_lat' => (float)$order['lat'],
  550. 'receiver_lng' => (float)$order['long'],
  551. 'callback' => $callbackUrl,
  552. 'cargo_weight' => isset($order['weight']) ? (float)$order['weight'] : 1.0,
  553. 'receiver_phone' => Functions::getMobile($order),
  554. //'tips' => 0, //小费(单位:元,精确小数点后一位,小费金额不能高于订单金额。)
  555. 'info' => $order['remark'] ?? '',
  556. 'product_list' => $productList,
  557. ];
  558. }
  559. /**
  560. * 准备滴滴订单数据
  561. */
  562. private function prepareDidiData($order, $shop)
  563. {
  564. return [
  565. 'platform' => 'didi',
  566. 'sender' => [
  567. 'fromSenderName' => $shop['merchantName'],
  568. 'fromMobile' => $shop['mobile'],
  569. 'fromAddress' => $shop['address'],
  570. 'fromAddressDetail' => $shop['floor'],
  571. 'fromLatitude' => (float)$shop['lat'],
  572. 'fromLongitude' => (float)$shop['long'],
  573. ],
  574. 'receiverList' => [
  575. [
  576. 'toReceiverName' => $order['customName'],
  577. 'toMobile' => Functions::getMobile($order),
  578. 'toAddress' => $order['address'],
  579. 'toAddressDetail' => $order['floor'],
  580. 'toLatitude' => (float)$order['lat'],
  581. 'toLongitude' => (float)$order['long'],
  582. 'weight' => isset($order['weight']) ? (float)$order['weight'] : 1.0,
  583. 'goodType' => 8,
  584. ]
  585. ]
  586. ];
  587. }
  588. /**
  589. * 并发获取各平台报价(核心实现)
  590. *
  591. * 使用 HttpClient::postConcurrent 实现真正的并发调用,每个平台请求 5 秒超时。
  592. * 某个平台的超时或失败不会影响其他平台的执行。
  593. *
  594. * @param array $preparedData 准备好的各平台数据
  595. * @param string $orderTime 配送时间
  596. * @return array 包含成功和失败结果
  597. */
  598. private function concurrentGetPrices($preparedData, $orderTime)
  599. {
  600. $results = [
  601. 'success' => [],
  602. 'failed' => [],
  603. ];
  604. // 第一步:收集所有平台的请求信息
  605. $allRequests = [];
  606. $platformMapping = []; // 用于将请求标识映射回平台名称
  607. foreach ($preparedData as $platform => $data) {
  608. try {
  609. $adapterKey = $platform; //由于要支持特殊逻辑处理,把 $this->adapters[xxx] 的 xxx 单独取变量
  610. if (!isset($this->adapters[$platform])) {
  611. if($platform == 'shunfeng_1v1'){ //特殊处理 -- 专人直送的订单,使用顺丰平台适配器
  612. $adapterKey = 'shunfeng';
  613. } else {
  614. $results['failed'][$platform] = '平台适配器未初始化';
  615. Yii::warning("[DispatchService] {$platform} 平台适配器未初始化");
  616. continue;
  617. }
  618. }
  619. $adapter = $this->adapters[$adapterKey];
  620. // 根据平台类型调用相应的 buildPriceRequest(s) 方法
  621. if ($platform === 'huolala') {
  622. // 货拉拉返回多个请求(一个请求对应一个车型)
  623. $priceRequests = $adapter->buildPriceRequest($data, $orderTime);
  624. foreach ($priceRequests as $requestKey => $requestInfo) {
  625. $allRequests[$requestKey] = $requestInfo;
  626. $platformMapping[$requestKey] = ['platform' => 'huolala', 'data' => $data];
  627. }
  628. } else {
  629. // 其他平台各返回一个请求
  630. $requestInfo = $adapter->buildPriceRequest($data, $orderTime);
  631. $requestKey = "{$platform}_quote";
  632. $allRequests[$requestKey] = $requestInfo;
  633. $platformMapping[$requestKey] = ['platform' => $platform, 'data' => $data];
  634. }
  635. } catch (\Throwable $e) {
  636. $results['failed'][$platform] = "构建请求失败: {$e->getMessage()}";
  637. Yii::error("[DispatchService] {$platform} 构建请求异常: {$e->getMessage()}");
  638. }
  639. }
  640. if (empty($allRequests)) {
  641. return $results;
  642. }
  643. // 第二步:使用 postConcurrent 并发发送所有请求
  644. $startTime = microtime(true);
  645. $concurrentResults = HttpClient::postConcurrent($allRequests, 3);
  646. $totalDuration = microtime(true) - $startTime;
  647. Yii::info("[DispatchService] 所有报价请求完成 (" . round($totalDuration * 1000) . "ms)");
  648. // 第三步:处理并发请求的结果
  649. foreach ($concurrentResults['success'] as $requestKey => $response) {
  650. if (!isset($platformMapping[$requestKey])) {
  651. continue;
  652. }
  653. $mapping = $platformMapping[$requestKey];
  654. $platform = $mapping['platform'];
  655. $data = $mapping['data'];
  656. try {
  657. $adapterKey = $platform; //由于要支持特殊逻辑处理,把 $this->adapters[xxx] 的 xxx 单独取变量
  658. if($platform == 'shunfeng_1v1'){ //特殊处理 -- 专人直送的订单,使用顺丰平台适配器
  659. $adapterKey = 'shunfeng';
  660. }
  661. $adapter = $this->adapters[$adapterKey];
  662. $quote = null;
  663. if ($platform === 'huolala') {
  664. // 货拉拉的响应处理
  665. $quote = $adapter->processPriceResponse($response);
  666. if ($quote && !isset($results['success']['huolala'])) {
  667. // 第一次处理货拉拉的结果,初始化
  668. $results['success']['huolala'] = [
  669. 'platform' => 'huolala',
  670. 'city_id' => $data['city_id'],
  671. 'vehicle_type_list' => $data['vehicle_type_list'],
  672. 'price_info_list' => [],
  673. ];
  674. }
  675. $keyArr = explode('_', $requestKey);
  676. $vehicle_type_list_key = $keyArr[2];
  677. // 将该车型的报价加入到列表中
  678. if ($quote && isset($results['success']['huolala'])) {
  679. $results['success']['huolala']['price_info_list'][] = [
  680. 'calculate_price_info' => isset($quote['calculate_price_info_list']) ? $quote['calculate_price_info_list'][0] : [],
  681. 'vehicle_type' => $data['vehicle_type_list'][$vehicle_type_list_key]
  682. ];
  683. Yii::info("[DispatchService] {$platform} 报价成功");// . json_encode($quote));
  684. }
  685. } else {
  686. // 蜂鸟和闪送的响应处理
  687. $quote = $adapter->processPriceResponse($response);
  688. if ($quote && !isset($quote['error'])) {
  689. $quote['_duration'] = $totalDuration;
  690. $results['success'][$platform] = $quote;
  691. Yii::info("[DispatchService] {$platform} 报价成功");// . json_encode($quote));
  692. } else {
  693. $errorMsg = $quote['error'] ?? '报价返回数据为空';
  694. $results['failed'][$platform] = $errorMsg;
  695. Yii::warning("[DispatchService] {$platform} 报价返回错误: {$errorMsg}");
  696. }
  697. }
  698. } catch (\Throwable $e) {
  699. $results['failed'][$platform] = "处理响应失败: {$e->getMessage()}";
  700. Yii::error("[DispatchService] {$platform} 处理响应异常: {$e->getMessage()}");
  701. }
  702. }
  703. // 第四步:处理失败的请求
  704. foreach ($concurrentResults['failed'] as $requestKey => $errorMsg) {
  705. if (!isset($platformMapping[$requestKey])) {
  706. continue;
  707. }
  708. $platform = $platformMapping[$requestKey]['platform'];
  709. // 对于货拉拉,只记录某个车型失败,不影响整体平台状态
  710. if ($platform === 'huolala') {
  711. Yii::warning("[DispatchService] huolala 车型报价失败 ({$requestKey}): {$errorMsg}");
  712. } else {
  713. if (!isset($results['failed'][$platform])) {
  714. $results['failed'][$platform] = $errorMsg;
  715. Yii::error("[DispatchService] {$platform} 报价请求失败: {$errorMsg}");
  716. }
  717. }
  718. }
  719. // 为货拉拉添加元数据
  720. if (isset($results['success']['huolala'])) {
  721. $results['success']['huolala']['_duration'] = $totalDuration;
  722. }
  723. return $results;
  724. }
  725. public function openCitiesLists($platform)
  726. {
  727. $ap = $this->adapters[$platform];
  728. return $ap->cityList();
  729. }
  730. /**
  731. * 刷新 token
  732. */
  733. public function refreshToken($platform, $refreshToken, $data=[])
  734. {
  735. switch($platform) {
  736. case 'shansong':
  737. $auth = new \common\components\delivery\platform\shansong\Auth();
  738. $auth->refreshAccessToken($refreshToken);
  739. break;
  740. case 'huolala':
  741. $auth = new \common\components\delivery\platform\huolala\Auth();
  742. $auth->refreshAccessToken($refreshToken);
  743. break;
  744. case 'fengniao':
  745. $auth = new \common\components\delivery\platform\fengniao\Auth();
  746. $auth->refreshAccessToken($refreshToken, $data['merchantId']);
  747. break;
  748. case 'shunfeng':
  749. $auth = new \common\components\delivery\platform\shunfeng\Auth();
  750. $auth->refreshAccessToken($refreshToken);
  751. break;
  752. }
  753. }
  754. /**
  755. * 格式化各平台报价为前端展示格式
  756. *
  757. * @param array $platformQuotes 各平台报价结果(来自 getAllPlatformPrice)
  758. * @return array 格式化后的配送列表
  759. */
  760. public function formatPlatformQuotesForDisplay($platformQuotes)
  761. {
  762. $deliveryList = [];
  763. if (empty($platformQuotes['quotes'])) {
  764. return $deliveryList;
  765. }
  766. foreach ($platformQuotes['quotes'] as $platformKey => $item) {
  767. if(!isset($item['platform'])){
  768. Yii::error(json_encode($item));
  769. continue;
  770. }
  771. switch ($item['platform']) {
  772. case 'shunfeng':
  773. $deliveryList[] = [
  774. 'name' => '顺丰' . ($platformKey == 'shunfeng_1v1' ? ' (专送)' : ''),
  775. 'en_name' => 'shunfeng',
  776. 'price' => $item['real_pay_money'],
  777. 'distance' => $item['distance'],
  778. 'type' => '' . ($platformKey == 'shunfeng_1v1' ? '专人直送' : ''),
  779. 'isAble' => true
  780. ];
  781. break;
  782. case 'shansong':
  783. $deliveryList[] = [
  784. 'name' => '闪送',
  785. 'en_name' => 'shansong',
  786. 'price' => $item['total_amount'],
  787. 'distance' => $item['total_distance'],
  788. 'type' => '',
  789. 'issOrderNo' => $item['order_number'],
  790. 'isAble' => true
  791. ];
  792. break;
  793. case 'fengniao':
  794. // 循环遍历 goods_infos 数组,提取有效项的信息
  795. $validGoods = [];
  796. if (!empty($item['goods_infos']) && is_array($item['goods_infos'])) {
  797. foreach ($item['goods_infos'] as $good) {
  798. if (!empty($good['is_valid']) && $good['is_valid'] == 1) {
  799. $validGoods[] = [
  800. 'actual_delivery_amount_cent' => $good['actual_delivery_amount_cent'] ?? 0,
  801. 'service_goods_id' => $good['service_goods_id'] ?? ''
  802. ];
  803. $deliveryList[] = [
  804. 'name' => '蜂鸟'. ' (' .$good['base_goods_id'] . ')',
  805. 'base_goods_id' => $good['base_goods_id'],
  806. 'en_name' => 'fengniao',
  807. 'price' => $good['actual_delivery_amount_cent'],
  808. 'distance' => $item['distance'],
  809. 'valid_goods' => $validGoods,
  810. 'type' => $good['slogan'],
  811. 'isAble' => true
  812. ];
  813. } else {
  814. $deliveryList[] = [
  815. 'name' => '蜂鸟'. ' (' .$good['base_goods_id'] . ')',
  816. 'base_goods_id' => $good['base_goods_id'],
  817. 'en_name' => 'fengniao',
  818. 'price' => 0,
  819. 'distance' => $item['distance'],
  820. 'valid_goods' => $good,
  821. 'type' => $good['disable_reason'],
  822. 'isAble' => false
  823. ];
  824. }
  825. }
  826. }
  827. break;
  828. case 'huolala':
  829. foreach($item['price_info_list'] as $key => $arr) {
  830. $priceInfo = $arr['calculate_price_info'];
  831. $priceConditions = $priceInfo['price_conditions'] ?? []; //价格明细
  832. $distanceInfo = $priceInfo['distance_info'] ?? []; //距离信息
  833. $vehicleType = $arr['vehicle_type'];
  834. if(empty($priceConditions)){
  835. Yii::error('货拉拉 报价数据 priceConditions 为空:' . json_encode($item) . ' key: ' . $key);
  836. continue;
  837. }
  838. if(empty($distanceInfo)){
  839. Yii::warning('货拉拉 报价数据 distanceInfo 为空:' . json_encode($item) . ' key: ' . $key);
  840. }
  841. $priceCalculateId = $priceInfo['price_calculate_id'] ?? 0;
  842. if(!isset($priceInfo['price_calculate_id'])){
  843. Yii::warning('货拉拉 报价数据 priceInfo 缺少 price_calculate_id:' . json_encode($priceInfo) . ' key: ' . $key);
  844. }
  845. //车型信息
  846. $vehicleAttr = $priceInfo['vehicle_info']['vehicle_attr'] ?? [];
  847. if(empty($vehicleAttr)){
  848. Yii::info('货拉拉 报价数据 vehicleAttr 为空:' . ' key: ' . $key); //json_encode($priceInfo) .
  849. }
  850. $deliveryList[] = [
  851. 'name' => '货拉拉' . ' (' . $vehicleType['_meta']['vehicle_type'] . ')',
  852. 'vehicle_type' => $vehicleType['_meta']['vehicle_type'],
  853. 'en_name' => 'huolala',
  854. 'price' => !empty($priceConditions) ? $priceConditions[0]['price_info']['total_price'] : 0,
  855. 'distance' => !empty($distanceInfo) ? $distanceInfo['distance_total'] : 0,
  856. 'type' => $vehicleType['_meta']['vehicle_type'],
  857. 'isAble' => true,
  858. // ---------------------------------------------
  859. 'order_vehicle_id' => $vehicleType['order_vehicle_id'],
  860. 'city_id' => $item['city_id'],
  861. 'city_info_revision' => $vehicleType['city_info_revision'],
  862. // 下单需要透传的数据
  863. 'vehicle_std' => $vehicleType['vehicle_std'],
  864. 'spec_req' => $vehicleType['spec_req'],
  865. 'price_calculate_id' => $priceCalculateId,
  866. 'price_item_encryption' => !empty($priceConditions) ? $priceConditions[0]['price_item_encryption'] : '',
  867. 'vehicle_attr' => $vehicleAttr,
  868. 'commodity_info' => !empty($priceConditions) ? $priceConditions[0]['commodity_item'] : [],
  869. ];
  870. }
  871. break;
  872. case 'dada':
  873. $list = [
  874. 'name' => '达达',
  875. 'en_name' => 'dada',
  876. 'price' => $item['fee'],
  877. 'distance' => $item['distance'],
  878. 'type' => '',
  879. 'isAble' => true,
  880. // ---------------------------------------------
  881. 'deliverFee' => $item['deliverFee'],
  882. 'deliveryNo' => $item['deliveryNo'],
  883. ];
  884. if(isset($item['couponName']) && isset($item['couponFee'])){
  885. $list['couponName'] = $item['couponName'];
  886. $list['couponFee'] = $item['couponFee'];
  887. }
  888. $deliveryList[] = $list;
  889. break;
  890. case 'didi':
  891. if(!isset($item['estimateList'])){
  892. Yii::error('didi 报价数据为空:' . json_encode($item));
  893. continue;
  894. }
  895. foreach($item['estimateList'] as $arr) {
  896. $deliveryList[] = [
  897. 'name' => '滴滴' . ' (' . $arr['carType'] . ')',
  898. 'en_name' => 'didi',
  899. 'price' => $arr['fee'],
  900. 'distance' => $arr['distance'],
  901. 'type' => $arr['estimateId'],
  902. 'isAble' => true,
  903. // ---------------------------------------------
  904. 'estimateId' => $arr['estimateId'],
  905. 'bizType' => $arr['bizType'],
  906. 'discountFee' => $arr['discountFee'],
  907. 'icon' => $arr['icon']
  908. ];
  909. }
  910. break;
  911. }
  912. }
  913. return $deliveryList;
  914. }
  915. }