DispatchService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <?php
  2. namespace common\components\delivery\services;
  3. use biz\shop\classes\ShopClass;
  4. use bizGhs\express\classes\DeliveryAuthTokenClass;
  5. use bizGhs\order\classes\OrderClass;
  6. use bizGhs\order\classes\OrderItemClass;
  7. use common\components\delivery\helpers\HttpClient;
  8. use common\components\delivery\services\adapter\{ ShansongAdapter, HuolalaAdapter, FengniaoAdapter}; // MeituanAdapter, DadaAdapter, SFAdapter, UUAdapter,
  9. use common\components\delivery\models\{DeliveryOrder, DeliveryAccount};
  10. use Yii;
  11. /**
  12. * 聚合调度逻辑(平台选择/优先级)
  13. * Class DispatchService
  14. * @package App\Services
  15. */
  16. class DispatchService
  17. {
  18. protected $adapters;
  19. protected $platformName = '';
  20. public function __construct($mainId, $platform='')
  21. {
  22. if ($platform == '') {
  23. $authPlatforms = DeliveryAuthTokenClass::getAllByCondition(['mainId'=>$mainId]);
  24. foreach($authPlatforms as $pt) {
  25. switch ($pt['platform']) {
  26. case 'shansong':
  27. $this->adapters['shansong'] = new ShansongAdapter($pt['accessToken']);
  28. break;
  29. case 'huolala':
  30. $this->adapters['huolala'] = new HuolalaAdapter($pt['accessToken']);
  31. break;
  32. case 'fengniao':
  33. $adapter = new FengniaoAdapter($pt['accessToken']);
  34. $adapter->setMerchantId(14594092); // TODO: 确认是否需要使用动态的商户ID
  35. $this->adapters['fengniao'] = $adapter;
  36. break;
  37. }
  38. }
  39. } else {
  40. $authPlatform = DeliveryAuthTokenClass::getByCondition(['mainId'=>$mainId, 'platform'=>$platform]);
  41. switch ($platform) {
  42. case 'shansong':
  43. $this->adapters['shansong'] = new ShansongAdapter($authPlatform['accessToken']);
  44. break;
  45. case 'huolala':
  46. $this->adapters['huolala'] = new HuolalaAdapter($authPlatform['accessToken']);
  47. break;
  48. case 'fengniao':
  49. //$this->adapters['fengniao'] = new FengniaoAdapter($authPlatform['accessToken']);
  50. $adapter = new FengniaoAdapter($authPlatform['accessToken']);
  51. $adapter->setMerchantId(14594092); // TODO: 确认是否需要使用动态的商户ID
  52. $this->adapters['fengniao'] = $adapter;
  53. break;
  54. }
  55. $this->platformName = $platform;
  56. }
  57. //$this->adapters = [
  58. //'meituan' => new MeituanAdapter(),
  59. //'dada' => new DadaAdapter(),
  60. //'sf' => new SFAdapter(),
  61. //'uu' => new UUAdapter(),
  62. //'fengniao' => new FengniaoAdapter(),
  63. //];
  64. }
  65. /**
  66. * 发单调度
  67. */
  68. public function createOrder($order, $shopId, $params)
  69. {
  70. $order = $order->toArray();
  71. $shop = ShopClass::getById($shopId);
  72. $adapter = $this->getAdapter();
  73. $orderData = $adapter->formatOrderData($order, $shop, $params);
  74. return $adapter->createOrder($orderData);
  75. }
  76. /**
  77. * @param $orderId 平台订单号
  78. * @param string $thirdOrderNo xhGhsOrder.orderSn
  79. */
  80. public function selectOrder($orderId, $thirdOrderNo='')
  81. {
  82. $adapter = $this->getAdapter();
  83. if ($adapter instanceof ShansongAdapter) {
  84. return $adapter->selectOrder($orderId, $thirdOrderNo);
  85. }
  86. return $adapter->selectOrder($orderId);
  87. }
  88. public function cancelOrder($orderId, $reason)
  89. {
  90. $adapter = $this->getAdapter();
  91. return $adapter->cancelOrder($orderId, $reason);
  92. }
  93. public function getCancelReasonList($orderId)
  94. {
  95. $adapter = $this->getAdapter();
  96. return $adapter->getCancelReasonList($orderId);
  97. }
  98. public function getAdapter()
  99. {
  100. return $this->adapters[$this->platformName];
  101. }
  102. /**
  103. * 获取所有平台的最佳报价(使用 Guzzle 并发请求)
  104. *
  105. * 流程说明:
  106. * 1. 同步准备各平台的前置数据(如城市信息、订单商品等)
  107. * 2. 使用 Guzzle Pool 并发发送各平台的报价请求(5秒超时)
  108. * 3. 某个平台失败/超时不影响其他平台,继续等待结果
  109. *
  110. * @param array $order 订单信息
  111. * @param array $shop 店铺信息
  112. * @return array 返回所有平台的报价结果
  113. */
  114. public function getAllPlatformPrice($order, $shop, $orderTime)
  115. {
  116. // 第一步:准备前置数据(同步进行,因为某些平台需要这些数据)
  117. $preparedData = $this->preparePlatformData($order, $shop, $orderTime);
  118. if (empty($preparedData)) {
  119. return ['error' => '所有平台数据准备失败'];
  120. }
  121. // 第二步:并发调用各平台的报价接口
  122. $results = $this->concurrentGetPrices($preparedData, $orderTime);
  123. if (empty($results['success']) && empty($results['failed'])) {
  124. return ['error' => '没有可用的物流平台'];
  125. }
  126. // 格式化返回结果
  127. return [
  128. 'quotes' => array_values($results['success'] ?? []),
  129. 'failed' => $results['failed'] ?? [],
  130. ];
  131. }
  132. /**
  133. * 为各平台准备订单数据(前置数据同步获取)
  134. *
  135. * @param array $order 订单信息
  136. * @param array $shop 店铺信息
  137. * @return array 各平台的订单数据
  138. */
  139. private function preparePlatformData($order, $shop)
  140. {
  141. $preparedData = [];
  142. // 准备 Huolala 数据
  143. if (isset($this->adapters['huolala'])) {
  144. try {
  145. $preparedData['huolala'] = $this->prepareHuolalaData($order, $shop);
  146. } catch (\Exception $e) {
  147. Yii::warning("Huolala 数据准备失败: {$e->getMessage()}");
  148. }
  149. }
  150. // 准备 Fengniao 数据
  151. if (isset($this->adapters['fengniao'])) {
  152. try {
  153. $preparedData['fengniao'] = $this->prepareFengniaoData($order, $shop);
  154. } catch (\Exception $e) {
  155. Yii::warning("Fengniao 数据准备失败: {$e->getMessage()}");
  156. }
  157. }
  158. // 准备 Shansong 数据
  159. if (isset($this->adapters['shansong'])) {
  160. try {
  161. $preparedData['shansong'] = $this->prepareShansongData($order, $shop);
  162. } catch (\Exception $e) {
  163. Yii::warning("Shansong 数据准备失败: {$e->getMessage()}");
  164. }
  165. }
  166. return $preparedData;
  167. }
  168. /**
  169. * 准备货拉拉订单数据
  170. */
  171. private function prepareHuolalaData($order, $shop)
  172. {
  173. $formatCity = rtrim($order['city'], '市');
  174. $cities = include Yii::getAlias('@common/components/delivery/platform/huolala/cities.php');
  175. if (!isset($cities[$formatCity])) {
  176. throw new \Exception('城市编码表中没有找到城市: ' . $formatCity);
  177. }
  178. $cityId = $cities[$formatCity]['city_id'];
  179. $cityVehicleList = $this->adapters['huolala']->getCityVehicleList($cityId); // 产生外部请求 -- TODO 优化成不耗时等待
  180. $cityInfoRevision = $cityVehicleList['city_info_revision'];
  181. // 获取所有车型列表
  182. $vehicleList = $cityVehicleList['vehicle_list'];
  183. if (empty($vehicleList)) {
  184. throw new \Exception('没有找到可选车型');
  185. }
  186. // 解析额外需求
  187. $specReqItem = $cityVehicleList['spec_req_item'] ?? [];
  188. $specReq = [];
  189. foreach ($specReqItem as $item) {
  190. $specReq[] = $item['type'] ?? null;
  191. }
  192. $specReq = array_filter($specReq);
  193. // 构建所有车型数据
  194. $vehicleTypeList = [];
  195. foreach ($vehicleList as $vehicle) {
  196. $vehicleStd = [];
  197. $vehicleStd[] = count($vehicle['vehicle_std_item']) > 0 ? $vehicle['vehicle_std_item'][0]['name'] : '';
  198. $vehicleTypeList[$vehicle['order_vehicle_id']] = [
  199. 'order_vehicle_id' => $vehicle['order_vehicle_id'],
  200. 'city_info_revision' => $cityInfoRevision,
  201. 'order_time' => time() + 600,
  202. 'addr_info' => [
  203. [
  204. 'name' => $shop['merchantName'],
  205. 'addr' => $shop['province'] . $shop['city'] . $shop['dist'] . $shop['address'],
  206. 'city_id' => $cityId,
  207. 'city_name' => $shop['city'],
  208. 'district_name' => $shop['dist'],
  209. 'house_number' => $shop['floor'],
  210. 'contacts_name' => $shop['mobile'],
  211. 'contacts_phone_no' => $shop['mobile'],
  212. 'lat_lon' => ['lat' => (float)$shop['lat'], 'lon' => (float)$shop['long']],
  213. ],
  214. [
  215. 'name' => $order['customName'],
  216. 'addr' => $order['fullAddress'],
  217. 'city_id' => $cityId,
  218. 'city_name' => $order['city'],
  219. 'district_name' => $order['dist'],
  220. 'house_number' => $order['floor'],
  221. 'contacts_name' => $order['customName'],
  222. 'contacts_phone_no' => $order['customMobile'],
  223. 'lat_lon' => ['lat' => (float)$order['lat'], 'lon' => (float)$order['long']],
  224. ]
  225. ],
  226. 'vehicle_std' => $vehicleStd,
  227. 'spec_req' => array_values($specReq),
  228. 'coupon_id' => 123456,
  229. 'invoice_type' => 1,
  230. 'order_service_type' => 1,
  231. '_meta' => [
  232. 'vehicle_type' => $vehicle['vehicle_name'],
  233. 'city_info_revision' => $cityInfoRevision,
  234. ]
  235. ];
  236. }
  237. return [
  238. 'platform' => 'huolala',
  239. 'city_id' => $cityId,
  240. 'vehicle_type_list' => $vehicleTypeList,
  241. ];
  242. }
  243. /**
  244. * 准备蜂鸟订单数据
  245. */
  246. private function prepareFengniaoData($order, $shop)
  247. {
  248. $this->adapters['fengniao']->setMerchantId(14594092); // TODO: 确认是否需要使用动态的商户ID
  249. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num');
  250. $goodsItemList = [];
  251. foreach ($itemInfos as $item) {
  252. $goodsItemList[] = [
  253. 'item_actual_amount_cent' => (int)($item['unitPrice'] * 100 * $item['num']),
  254. 'item_amount_cent' => (int)($item['unitPrice'] * 100),
  255. 'item_id' => $item['id'],
  256. 'item_name' => $item['name'],
  257. 'item_quantity' => $item['num'],
  258. ];
  259. }
  260. return [
  261. 'platform' => 'fengniao',
  262. 'partner_order_code' => $order['orderSn'],
  263. 'receiver_primary_phone' => $order['customMobile'],
  264. 'receiver_name' => $order['customName'],
  265. 'receiver_latitude' => (float)$order['lat'],
  266. 'receiver_longitude' => (float)$order['long'],
  267. 'receiver_address' => $order['fullAddress'],
  268. 'position_source' => 3,
  269. 'goods_count' => count($goodsItemList),
  270. 'goods_weight' => (float)$order['weight'],
  271. 'goods_total_amount_cent' => (int)($order['prePrice'] * 100),
  272. 'goods_actual_amount_cent' => (int)($order['actPrice'] * 100),
  273. 'goods_item_list' => $goodsItemList,
  274. 'order_type' => 1,
  275. 'chain_store_id' => 467788524,
  276. 'order_remark' => $order['remark'] ?? '',
  277. ];
  278. }
  279. /**
  280. * 准备闪送订单数据
  281. */
  282. private function prepareShansongData($order, $shop)
  283. {
  284. return [
  285. 'platform' => 'shansong',
  286. 'city_name' => $shop['city'],
  287. 'sender' => [
  288. 'from_address' => $shop['address'],
  289. 'from_address_detail' => $shop['floor'],
  290. 'from_sender_name' => $shop['shopName'],
  291. 'from_mobile' => $shop['mobile'],
  292. 'from_latitude' => (float)$shop['lat'],
  293. 'from_longitude' => (float)$shop['long'],
  294. ],
  295. 'receiver_list' => [
  296. [
  297. 'order_no' => $order['orderSn'],
  298. 'to_address' => $order['address'],
  299. 'to_address_detail' => $order['floor'],
  300. 'to_receiver_name' => $order['customName'],
  301. 'to_mobile' => $order['customMobile'],
  302. 'to_latitude' => (float)$order['lat'],
  303. 'to_longitude' => (float)$order['long'],
  304. 'good_type' => 7,
  305. 'weight' => (int)$order['weight'],
  306. 'remarks' => $order['remark'] ?? '',
  307. ]
  308. ],
  309. 'appoint_type' => 0,
  310. 'appointment_date' => '',
  311. 'travel_way' => 0,
  312. 'delivery_type' => 1,
  313. 'expect_start_time' => null,
  314. 'expect_end_time' => null,
  315. ];
  316. }
  317. /**
  318. * 并发获取各平台报价(核心实现)
  319. *
  320. * 使用 HttpClient::postConcurrent 实现真正的并发调用,每个平台请求 5 秒超时。
  321. * 某个平台的超时或失败不会影响其他平台的执行。
  322. *
  323. * @param array $preparedData 准备好的各平台数据
  324. * @param string $orderTime 配送时间
  325. * @return array 包含成功和失败结果
  326. */
  327. private function concurrentGetPrices($preparedData, $orderTime)
  328. {
  329. $results = [
  330. 'success' => [],
  331. 'failed' => [],
  332. ];
  333. // 第一步:收集所有平台的请求信息
  334. $allRequests = [];
  335. $platformMapping = []; // 用于将请求标识映射回平台名称
  336. foreach ($preparedData as $platform => $data) {
  337. try {
  338. if (!isset($this->adapters[$platform])) {
  339. $results['failed'][$platform] = '平台适配器未初始化';
  340. continue;
  341. }
  342. $adapter = $this->adapters[$platform];
  343. // 根据平台类型调用相应的 buildPriceRequest(s) 方法
  344. if ($platform === 'huolala') {
  345. // 货拉拉返回多个请求(一个请求对应一个车型)
  346. $priceRequests = $adapter->buildPriceRequests($data, $orderTime);
  347. foreach ($priceRequests as $requestKey => $requestInfo) {
  348. $allRequests[$requestKey] = $requestInfo;
  349. $platformMapping[$requestKey] = ['platform' => 'huolala', 'data' => $data];
  350. }
  351. } else {
  352. // 其他平台(蜂鸟、闪送)各返回一个请求
  353. $requestInfo = $adapter->buildPriceRequest($data, $orderTime);
  354. $requestKey = "{$platform}_quote";
  355. $allRequests[$requestKey] = $requestInfo;
  356. $platformMapping[$requestKey] = ['platform' => $platform, 'data' => $data];
  357. }
  358. } catch (\Throwable $e) {
  359. $results['failed'][$platform] = "构建请求失败: {$e->getMessage()}";
  360. Yii::error("[DispatchService] {$platform} 构建请求异常: {$e->getMessage()}");
  361. }
  362. }
  363. if (empty($allRequests)) {
  364. return $results;
  365. }
  366. // 第二步:使用 postConcurrent 并发发送所有请求
  367. $startTime = microtime(true);
  368. $concurrentResults = HttpClient::postConcurrent($allRequests, 3);
  369. $totalDuration = microtime(true) - $startTime;
  370. Yii::info("[DispatchService] 所有报价请求完成 (" . round($totalDuration * 1000) . "ms)");
  371. // 第三步:处理并发请求的结果
  372. foreach ($concurrentResults['success'] as $requestKey => $response) {
  373. if (!isset($platformMapping[$requestKey])) {
  374. continue;
  375. }
  376. $mapping = $platformMapping[$requestKey];
  377. $platform = $mapping['platform'];
  378. $data = $mapping['data'];
  379. try {
  380. $adapter = $this->adapters[$platform];
  381. $quote = null;
  382. if ($platform === 'huolala') {
  383. // 货拉拉的响应处理
  384. $quote = $adapter->processPriceResponse($response);
  385. if ($quote && !isset($results['success']['huolala'])) {
  386. // 第一次处理货拉拉的结果,初始化
  387. $results['success']['huolala'] = [
  388. 'platform' => 'huolala',
  389. 'city_id' => $data['city_id'],
  390. 'vehicle_type_list' => $data['vehicle_type_list'],
  391. 'price_info_list' => [],
  392. ];
  393. }
  394. $keyArr = explode('_', $requestKey);
  395. $vehicle_type_list_key = $keyArr[2];
  396. // 将该车型的报价加入到列表中
  397. if ($quote && isset($results['success']['huolala'])) {
  398. $results['success']['huolala']['price_info_list'][] = [
  399. 'calculate_price_info' => isset($quote['calculate_price_info_list']) ? $quote['calculate_price_info_list'][0] : [],
  400. 'vehicle_type' => $data['vehicle_type_list'][$vehicle_type_list_key]
  401. ];
  402. }
  403. } else {
  404. // 蜂鸟和闪送的响应处理
  405. $quote = $adapter->processPriceResponse($response);
  406. if ($quote && !isset($quote['error'])) {
  407. $quote['_duration'] = $totalDuration;
  408. $results['success'][$platform] = $quote;
  409. Yii::info("[DispatchService] {$platform} 报价成功 (" . round($totalDuration * 1000) . "ms)");
  410. } else {
  411. $errorMsg = $quote['error'] ?? '报价返回数据为空';
  412. $results['failed'][$platform] = $errorMsg;
  413. Yii::warning("[DispatchService] {$platform} 报价返回错误: {$errorMsg}");
  414. }
  415. }
  416. } catch (\Throwable $e) {
  417. $platform = $mapping['platform'];
  418. $results['failed'][$platform] = "处理响应失败: {$e->getMessage()}";
  419. Yii::error("[DispatchService] {$platform} 处理响应异常: {$e->getMessage()}");
  420. }
  421. }
  422. // 第四步:处理失败的请求
  423. foreach ($concurrentResults['failed'] as $requestKey => $errorMsg) {
  424. if (!isset($platformMapping[$requestKey])) {
  425. continue;
  426. }
  427. $platform = $platformMapping[$requestKey]['platform'];
  428. // 对于货拉拉,只记录某个车型失败,不影响整体平台状态
  429. if ($platform === 'huolala') {
  430. Yii::warning("[DispatchService] huolala 车型报价失败 ({$requestKey}): {$errorMsg}");
  431. } else {
  432. if (!isset($results['failed'][$platform])) {
  433. $results['failed'][$platform] = $errorMsg;
  434. Yii::error("[DispatchService] {$platform} 报价请求失败: {$errorMsg}");
  435. }
  436. }
  437. }
  438. // 为货拉拉添加元数据
  439. if (isset($results['success']['huolala'])) {
  440. $results['success']['huolala']['_duration'] = $totalDuration;
  441. }
  442. return $results;
  443. }
  444. public function openCitiesLists($platform)
  445. {
  446. $ap = $this->adapters[$platform];
  447. return $ap->cityList();
  448. }
  449. }