DispatchService.php 37 KB

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