DispatchService.php 37 KB

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