DispatchService.php 38 KB

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