DispatchService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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['access_token']);
  28. break;
  29. case 'huolala':
  30. $this->adapters['huolala'] = new HuolalaAdapter($pt['access_token']);
  31. break;
  32. case 'fengniao':
  33. $adapter = new FengniaoAdapter($pt['access_token']);
  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['access_token']);
  44. break;
  45. case 'huolala':
  46. $this->adapters['huolala'] = new HuolalaAdapter($authPlatform['access_token']);
  47. break;
  48. case 'fengniao':
  49. //$this->adapters['fengniao'] = new FengniaoAdapter($authPlatform['access_token']);
  50. $adapter = new FengniaoAdapter($authPlatform['access_token']);
  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 getBestPlatformByPrice($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, $orderTime)
  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. $selectVehicle = [];
  184. $vehicleType = '';
  185. $vehicleStd = [];
  186. // 优先选择 "跑腿"
  187. foreach ($vehicleList as $vehicle) {
  188. if ($vehicle['vehicle_name'] == '跑腿') {
  189. $selectVehicle = $vehicle;
  190. $vehicleType = '跑腿';
  191. $vehicleStd[] = count($vehicle['vehicle_std_item']) > 0 ? $vehicle['vehicle_std_item'][0]['name'] : '';
  192. break;
  193. }
  194. }
  195. // 如果没有 "跑腿",选择 "二轮车" 或 "面包车"
  196. if (empty($selectVehicle)) {
  197. $erLunVehicle = [];
  198. $mianBaoVehicle = [];
  199. foreach ($vehicleList as $vehicle) {
  200. if ($vehicle['vehicle_name'] == '二轮车') {
  201. $erLunVehicle = $vehicle;
  202. $vehicleType = '二轮车';
  203. $vehicleStd[] = count($vehicle['vehicle_std_item']) > 0 ? $vehicle['vehicle_std_item'][0]['name'] : '';
  204. }
  205. if (in_array($vehicle['vehicle_name'], ['微面', '小面车', '小面包车'])) {
  206. $mianBaoVehicle = $vehicle;
  207. $vehicleType = $vehicle['vehicle_name'];
  208. $vehicleStd[] = count($vehicle['vehicle_std_item']) > 0 ? $vehicle['vehicle_std_item'][0]['name'] : '';
  209. }
  210. }
  211. $selectVehicle = !empty($erLunVehicle) ? $erLunVehicle : $mianBaoVehicle;
  212. }
  213. if (empty($selectVehicle)) {
  214. throw new \Exception('没有找到可选车型');
  215. }
  216. // 解析额外需求
  217. $specReqItem = $cityVehicleList['spec_req_item'] ?? [];
  218. $specReq = [];
  219. foreach ($specReqItem as $item) {
  220. $specReq[] = $item['type'] ?? null;
  221. }
  222. $specReq = array_filter($specReq);
  223. return [
  224. 'platform' => 'huolala',
  225. 'city_id' => $cityId,
  226. 'order_vehicle_id' => $selectVehicle['order_vehicle_id'],
  227. 'city_info_revision' => $cityInfoRevision,
  228. 'order_time' => time() + 600,
  229. 'addr_info' => [
  230. [
  231. 'name' => $shop['merchantName'],
  232. 'addr' => $shop['province'] . $shop['city'] . $shop['dist'] . $shop['address'],
  233. 'city_id' => $cityId,
  234. 'city_name' => $shop['city'],
  235. 'district_name' => $shop['dist'],
  236. 'house_number' => $shop['floor'],
  237. 'contacts_name' => $shop['mobile'],
  238. 'contacts_phone_no' => $shop['mobile'],
  239. 'lat_lon' => ['lat' => (float)$shop['lat'], 'lon' => (float)$shop['long']],
  240. ],
  241. [
  242. 'name' => $order['customName'],
  243. 'addr' => $order['fullAddress'],
  244. 'city_id' => $cityId,
  245. 'city_name' => $order['city'],
  246. 'district_name' => $order['dist'],
  247. 'house_number' => $order['floor'],
  248. 'contacts_name' => $order['customName'],
  249. 'contacts_phone_no' => $order['customMobile'],
  250. 'lat_lon' => ['lat' => (float)$order['lat'], 'lon' => (float)$order['long']],
  251. ]
  252. ],
  253. 'vehicle_std' => $vehicleStd,
  254. 'spec_req' => array_values($specReq),
  255. 'coupon_id' => 123456,
  256. 'invoice_type' => 1,
  257. 'order_service_type' => 1,
  258. '_meta' => [
  259. 'vehicle_type' => $vehicleType,
  260. 'city_info_revision' => $cityInfoRevision,
  261. ]
  262. ];
  263. }
  264. /**
  265. * 准备蜂鸟订单数据
  266. */
  267. private function prepareFengniaoData($order, $shop)
  268. {
  269. $this->adapters['fengniao']->setMerchantId(14594092); // TODO: 确认是否需要使用动态的商户ID
  270. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num');
  271. $goodsItemList = [];
  272. foreach ($itemInfos as $item) {
  273. $goodsItemList[] = [
  274. 'item_actual_amount_cent' => (int)($item['unitPrice'] * 100 * $item['num']),
  275. 'item_amount_cent' => (int)($item['unitPrice'] * 100),
  276. 'item_id' => $item['id'],
  277. 'item_name' => $item['name'],
  278. 'item_quantity' => $item['num'],
  279. ];
  280. }
  281. return [
  282. 'platform' => 'fengniao',
  283. 'partner_order_code' => $order['orderSn'],
  284. 'receiver_primary_phone' => $order['customMobile'],
  285. 'receiver_name' => $order['customName'],
  286. 'receiver_latitude' => (float)$order['lat'],
  287. 'receiver_longitude' => (float)$order['long'],
  288. 'receiver_address' => $order['fullAddress'],
  289. 'position_source' => 3,
  290. 'goods_count' => count($goodsItemList),
  291. 'goods_weight' => (float)$order['weight'],
  292. 'goods_total_amount_cent' => (int)($order['prePrice'] * 100),
  293. 'goods_actual_amount_cent' => (int)($order['actPrice'] * 100),
  294. 'goods_item_list' => $goodsItemList,
  295. 'order_type' => 1,
  296. 'chain_store_id' => 467788524,
  297. 'order_remark' => $order['remark'] ?? '',
  298. ];
  299. }
  300. /**
  301. * 准备闪送订单数据
  302. */
  303. private function prepareShansongData($order, $shop)
  304. {
  305. return [
  306. 'platform' => 'shansong',
  307. 'city_name' => $shop['city'],
  308. 'sender' => [
  309. 'from_address' => $shop['address'],
  310. 'from_address_detail' => $shop['floor'],
  311. 'from_sender_name' => $shop['shopName'],
  312. 'from_mobile' => $shop['mobile'],
  313. 'from_latitude' => (float)$shop['lat'],
  314. 'from_longitude' => (float)$shop['long'],
  315. ],
  316. 'receiver_list' => [
  317. [
  318. 'order_no' => $order['orderSn'],
  319. 'to_address' => $order['address'],
  320. 'to_address_detail' => $order['floor'],
  321. 'to_receiver_name' => $order['customName'],
  322. 'to_mobile' => $order['customMobile'],
  323. 'to_latitude' => (float)$order['lat'],
  324. 'to_longitude' => (float)$order['long'],
  325. 'good_type' => 7,
  326. 'weight' => (int)$order['weight'],
  327. 'remarks' => $order['remark'] ?? '',
  328. ]
  329. ],
  330. 'appoint_type' => 0,
  331. 'appointment_date' => '',
  332. 'travel_way' => 0,
  333. 'delivery_type' => 1,
  334. 'expect_start_time' => null,
  335. 'expect_end_time' => null,
  336. ];
  337. }
  338. /**
  339. * 并发获取各平台报价(核心实现)
  340. *
  341. * 使用 Guzzle Pool 实现真正的并发调用,每个平台请求 5 秒超时。
  342. * 某个平台的超时或失败不会影响其他平台的执行。
  343. *
  344. * @param array $preparedData 准备好的各平台数据
  345. * @param string $orderTime 配送时间
  346. * @return array 包含成功和失败结果
  347. */
  348. private function concurrentGetPrices($preparedData, $orderTime)
  349. {
  350. $results = [
  351. 'success' => [],
  352. 'failed' => [],
  353. ];
  354. // 如果 PHP 不支持真正的异步,采用顺序调用(但每个请求应用超时)
  355. // 这是 PHP 同步框架的限制,通过 set_time_limit 和超时配置来模拟效果
  356. foreach ($preparedData as $platform => $data) {
  357. try {
  358. if (!isset($this->adapters[$platform])) {
  359. $results['failed'][$platform] = '平台适配器未初始化';
  360. continue;
  361. }
  362. $adapter = $this->adapters[$platform];
  363. $startTime = microtime(true);
  364. // 这里调用适配器的 getPrice 方法,该方法内部会使用 HttpClient
  365. // 在 HttpClient 中配置的超时会被应用
  366. $quote = $adapter->getPrice($data, $orderTime);
  367. $duration = microtime(true) - $startTime;
  368. if ($quote && !isset($quote['error'])) {
  369. // 添加平台标识和元数据
  370. $quote['platform'] = $platform;
  371. $quote['_duration'] = $duration;
  372. // 针对不同平台的数据处理
  373. if ($platform === 'huolala' && isset($data['_meta'])) {
  374. $quote['city_id'] = $data['city_id'];
  375. $quote['city_info_revision'] = $data['_meta']['city_info_revision'] ?? '';
  376. $quote['vehicle_type'] = $data['_meta']['vehicle_type'] ?? '';
  377. $quote['spec_req'] = $data['spec_req'] ?? [];
  378. $quote['vehicle_std'] = $data['vehicle_std'] ?? [];
  379. }
  380. $results['success'][$platform] = $quote;
  381. Yii::info("[DispatchService] {$platform} 报价成功 (" . round($duration * 1000) . "ms)");
  382. } else {
  383. $errorMsg = $quote['error'] ?? '报价返回数据为空';
  384. $results['failed'][$platform] = $errorMsg;
  385. Yii::warning("[DispatchService] {$platform} 报价返回错误: {$errorMsg}");
  386. }
  387. } catch (\Throwable $e) {
  388. $results['failed'][$platform] = $e->getMessage();
  389. Yii::error("[DispatchService] {$platform} 报价异常: {$e->getMessage()}");
  390. }
  391. }
  392. return $results;
  393. }
  394. public function openCitiesLists($platform)
  395. {
  396. $ap = $this->adapters[$platform];
  397. return $ap->cityList();
  398. }
  399. }