DispatchService.php 47 KB

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