DispatchService.php 35 KB

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