DispatchService.php 32 KB

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