DispatchService.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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 = $this->adapters['shunfeng']->getCustomSettings();
  282. $customSettings = [];//自定义用户设置:默认不专人直送
  283. $preparedData['shunfeng'] = $this->prepareShunfengData($order, $shop, $customSettings);
  284. }
  285. //添加专人直送的订单数据
  286. if(in_array($isPersonDirect, [1, 2])){
  287. $customSettings = ['isPersonDirect' => 1];//自定义用户设置:专人直送
  288. $preparedData['shunfeng_1v1'] = $this->prepareShunfengData($order, $shop, $customSettings);
  289. Yii::info('预创建订单 shunfeng_1v1 request data: ' . json_encode($preparedData['shunfeng_1v1']));
  290. }
  291. } catch (\Exception $e) {
  292. Yii::warning("Shunfeng 数据准备失败: {$e->getMessage()}");
  293. }
  294. }
  295. // 准备达达订单数据
  296. if (isset($this->adapters['dada'])) {
  297. try {
  298. $dadaAdapter = $this->adapters['dada'];
  299. $shopNo = $dadaAdapter->getShopNo();
  300. $preparedData['dada'] = $this->prepareDadaData($order, $shop, $shopNo);
  301. } catch (\Exception $e) {
  302. Yii::warning("Dada 数据准备失败: {$e->getMessage()}");
  303. }
  304. }
  305. // 准备滴滴订单数据
  306. if (isset($this->adapters['didi'])) {
  307. try {
  308. $preparedData['didi'] = $this->prepareDidiData($order, $shop);
  309. } catch (\Exception $e) {
  310. Yii::warning("Didi 数据准备失败: {$e->getMessage()}");
  311. }
  312. }
  313. return $preparedData;
  314. }
  315. /**
  316. * 准备货拉拉订单数据
  317. */
  318. private function prepareHuolalaData($order, $shop)
  319. {
  320. $formatCity = rtrim($order['city'], '市');
  321. $cities = include Yii::getAlias('@common/components/delivery/platform/huolala/cities.php');
  322. if (!isset($cities[$formatCity])) {
  323. throw new \Exception('城市编码表中没有找到城市: ' . $formatCity);
  324. }
  325. $cityId = $cities[$formatCity]['city_id'];
  326. $cityVehicleList = $this->adapters['huolala']->getCityVehicleList($cityId); // 产生外部请求
  327. $cityInfoRevision = $cityVehicleList['city_info_revision']; // 城市版本号
  328. $vehicleList = $cityVehicleList['vehicle_list']; // 所有车型列表
  329. if (empty($vehicleList)) {
  330. throw new \Exception('没有找到可选车型');
  331. }
  332. // 解析额外需求
  333. $specReqItem = $cityVehicleList['spec_req_item'] ?? [];
  334. $specReq = [];
  335. foreach ($specReqItem as $item) {
  336. $specReq[] = $item['type'] ?? null;
  337. }
  338. $specReq = array_filter($specReq);
  339. // 构建所有车型数据
  340. $vehicleTypeList = [];
  341. foreach ($vehicleList as $vehicle) {
  342. if(!in_array($vehicle['vehicle_name'], ['跑腿', '小面', '微面'])){ // && !$this->adapters['huolala']->getIsSandbox()
  343. continue;
  344. }
  345. $vehicleStd = [];
  346. $vehicleStd[] = count($vehicle['vehicle_std_item']) > 0 ? $vehicle['vehicle_std_item'][0]['name'] : '';
  347. $vehicleTypeList[$vehicle['order_vehicle_id']] = [
  348. 'order_vehicle_id' => $vehicle['order_vehicle_id'],
  349. 'city_info_revision' => $cityInfoRevision,
  350. 'order_time' => time() + 600,
  351. 'addr_info' => [
  352. [
  353. 'name' => $shop['merchantName'],
  354. 'addr' => $shop['province'] . $shop['city'] . $shop['dist'] . $shop['address'],
  355. 'city_id' => $cityId,
  356. 'city_name' => $shop['city'],
  357. 'district_name' => $shop['dist'],
  358. 'house_number' => $shop['floor'],
  359. 'contacts_name' => $shop['mobile'],
  360. 'contacts_phone_no' => $shop['mobile'],
  361. 'lat_lon' => ['lat' => (float)$shop['lat'], 'lon' => (float)$shop['long']],
  362. ],
  363. [
  364. 'name' => $order['customName'],
  365. 'addr' => $order['fullAddress'],
  366. 'city_id' => $cityId,
  367. 'city_name' => $order['city'],
  368. 'district_name' => $order['dist'],
  369. 'house_number' => $order['floor'],
  370. 'contacts_name' => $order['customName'],
  371. 'contacts_phone_no' => Functions::getMobile($order),
  372. 'lat_lon' => ['lat' => (float)$order['lat'], 'lon' => (float)$order['long']],
  373. ]
  374. ],
  375. 'vehicle_std' => $vehicleStd,
  376. 'spec_req' => array_values($specReq),
  377. 'coupon_id' => 123456, // TODO ??? 添加自动获取 coupon_id
  378. 'invoice_type' => 1,
  379. 'order_service_type' => 1,
  380. '_meta' => [
  381. 'vehicle_type' => $vehicle['vehicle_name'],
  382. 'city_info_revision' => $cityInfoRevision,
  383. ]
  384. ];
  385. }
  386. return [
  387. 'platform' => 'huolala',
  388. 'city_id' => $cityId,
  389. 'vehicle_type_list' => $vehicleTypeList,
  390. ];
  391. }
  392. /**
  393. * 准备蜂鸟订单数据
  394. */
  395. private function prepareFengniaoData($order, $shop, $platformShopId)
  396. {
  397. // $this->adapters['fengniao']->setMerchantId(14594092); // adapter 创建时已经设置了
  398. $goodsItemList = [];
  399. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num');
  400. foreach ($itemInfos as $item) {
  401. $goodsItemList[] = [
  402. 'item_actual_amount_cent' => (int)($item['unitPrice'] * 100 * $item['num']),
  403. 'item_amount_cent' => (int)($item['unitPrice'] * 100),
  404. 'item_id' => $item['id'],
  405. 'item_name' => $item['name'],
  406. 'item_quantity' => $item['num'],
  407. ];
  408. }
  409. return [
  410. 'platform' => 'fengniao',
  411. 'partner_order_code' => $order['orderSn'],
  412. 'receiver_primary_phone' => Functions::getMobile($order),
  413. 'receiver_name' => $order['customName'],
  414. 'receiver_latitude' => (float)$order['lat'],
  415. 'receiver_longitude' => (float)$order['long'],
  416. 'receiver_address' => $order['fullAddress'],
  417. 'position_source' => 3,
  418. 'goods_count' => count($goodsItemList),
  419. 'goods_weight' => (float)$order['weight'],
  420. 'goods_total_amount_cent' => (int)($order['actPrice'] * 100),
  421. 'goods_actual_amount_cent' => (int)($order['prePrice'] * 100),
  422. 'goods_item_list' => $goodsItemList,
  423. 'order_type' => 1,
  424. 'chain_store_id' => $platformShopId, // 蜂鸟平台 shopId
  425. 'order_remark' => $order['remark'] ?? '',
  426. ];
  427. }
  428. /**
  429. * 准备闪送订单数据
  430. */
  431. private function prepareShansongData($order, $shop, $orderTime)
  432. {
  433. $data = [
  434. 'platform' => 'shansong',
  435. 'cityName' => $shop['city'],
  436. 'sender' => [
  437. 'fromAddress' => $shop['address'],
  438. 'fromAddressDetail' => $shop['floor'],
  439. 'fromSenderName' => $shop['shopName'] == '首店' ? $shop['merchantName'] : $shop['merchantName'].'-'.$shop['shopName'],
  440. 'fromMobile' => $shop['mobile'],
  441. 'fromLatitude' => (string)$shop['lat'],
  442. 'fromLongitude' => (string)$shop['long'],
  443. ],
  444. 'receiverList' => [
  445. [
  446. 'orderNo' => $order['orderSn'],
  447. 'toAddress' => $order['address'],
  448. 'toAddressDetail' => $order['floor'],
  449. 'toReceiverName' => $order['customName'],
  450. 'toMobile' => Functions::getMobile($order),
  451. 'toLatitude' => (string)$order['lat'],
  452. 'toLongitude' => (string)$order['long'],
  453. 'goodType' => 7, //鲜花
  454. 'weight' => (int)round($order['weight']),
  455. 'remarks' => $order['remark'] ?? '',
  456. ]
  457. ],
  458. 'appointType' => 0, //预约类型: 0立即单,1预约单
  459. 'travelWay' => 0,
  460. 'deliveryType' => 1,
  461. //补充额外的订单数据
  462. 'sendNum' => $order['sendNum'],
  463. ];
  464. $timestamp = strtotime($orderTime);
  465. $currentTime = time() + 3600;
  466. if($timestamp > $currentTime){
  467. $data['appointType'] = 1; // 修改预约类型
  468. $data['appointmentDate'] = $orderTime; // 预约时间, yyyy-MM-dd HH:mm格式(例如:2020-02-02 22:00),指的是预约取件时间,只支持一个小时以后两天以内
  469. // 'expectStartTime' 期望送达时间起始时间 -- 毫秒级时间戳。期望送达时间为时间点时,无需传本参数;期望送达时间为时间段时,期望送达时间为expectStartTime至expectEndTime
  470. // 'expectEndTime' 期望送达时间终止时间 -- 毫秒级时间戳。期望送达时间为时间点时,只需传本参数;期望送达时间为时间段时,期望送达时间为expectStartTime至expectEndTime
  471. $data['receiverList'][0]['expectStartTime'] = ($timestamp + 900) * 1000;
  472. $data['receiverList'][0]['expectEndTime'] = ($timestamp + 1800) * 1000;
  473. }
  474. return $data;
  475. }
  476. /**
  477. * 准备顺丰订单数据
  478. */
  479. private function prepareShunfengData($order, $shop, $customSettings)
  480. {
  481. // 获取订单商品信息
  482. // $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num, unitWeight');
  483. // 计算商品总重量(单位:克)
  484. // $totalWeight = 0;
  485. // foreach ($itemInfos as $item) {
  486. // $totalWeight += (int)($item['unitWeight'] * $item['num']) * 1000;
  487. // }
  488. // 如果没有商品重量,使用订单重量
  489. // if ($totalWeight == 0 && isset($order['weight'])) {
  490. // $totalWeight = (int)$order['weight'] * 1000;
  491. // }
  492. // 默认重量为1000克(1公斤)
  493. // if ($totalWeight == 0) {
  494. // $totalWeight = 1000;
  495. // }
  496. return [
  497. 'platform' => 'shunfeng',
  498. 'user_lng' => (string)$order['long'], // 用户地址经度
  499. 'user_lat' => (string)$order['lat'], // 用户地址纬度
  500. 'user_address' => $order['fullAddress'], // 用户详细地址
  501. 'weight' => $order['weight'] * 1000, // 物品重量(单位:克)
  502. 'product_type' => 4, // 物品类型(4:鲜花绿植)
  503. 'push_time' => time(), // 推单时间(秒级时间戳)
  504. //shop 平台级开发者需要传入
  505. 'shop' => [ // 发货店铺信息
  506. 'shop_name' => $shop['merchantName'], // 店铺名称
  507. 'shop_address' => $shop['fullAddress'], // 店铺地址
  508. 'shop_lng' => (string)$shop['long'], // 店铺经度
  509. 'shop_lat' => (string)$shop['lat'], // 店铺纬度
  510. 'shop_phone' => $shop['mobile'], // 店铺联系电话
  511. ],
  512. //-------------------------- 非必填 -------------------------------
  513. 'city_name' => $order['city'], // 发单城市
  514. //'order_source' => '6', // 订单接入来源(6:京东秒送,可自定义)
  515. 'source_origin_order_id' => $order['orderSn'], // 商流订单号
  516. 'total_price' => (int)($order['actPrice'] * 100), // 用户订单总金额(单位:分)
  517. 'is_appoint' => 0, // 是否预约单(0:非预约单)
  518. //'appoint_type' => 0, // 预约单的时候传入,1:预约送达单;2:预约上门单
  519. //'expect_pickup_time' => 0, // TODO 用户期望上门时间 -- appoint_type=2时需必传,秒级时间戳
  520. //'expect_time' => 0, // TODO 用户期望送达时间
  521. //'shop_expect_time' => 0, // TODO 商家期望送达时间 -- 格式为:{timestamp},
  522. 'lbs_type' => 2, // 坐标类型(2:高德坐标)
  523. 'is_insured' => 0, // 是否保价(0:非保价)
  524. 'is_person_direct' => $customSettings['isPersonDirect'] ?? 0, // 是否专人直送(0:否 1:是)
  525. 'vehicle' => 0, // 配送交通工具(0:否)
  526. //'four_wheeler_type' => 0, // 车型 -- 只有vehicle = 2,⻋型字段才有效。
  527. //'declared_value' => 0, // 保价金额(单位:分)
  528. //'gratuity_fee' => 0, // 订单小费(单位:分)
  529. 'rider_pick_method' => 1, // 物流流向(1:从门店取件送至用户)
  530. 'return_flag' => 511, // 返回字段控制标志位(511:全部返回)
  531. 'multi_pickup_info' => [], // 多点取货信息(暂不使用)
  532. ];
  533. }
  534. /**
  535. * 准备达达订单数据
  536. */
  537. private function prepareDadaData($order, $shop, $shopNo)
  538. {
  539. $productList = [];
  540. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num, bigNum, smallNum, xhUnitName');
  541. foreach ($itemInfos as $item) {
  542. $productList[] = [
  543. 'sku_name' => $item['name'],
  544. 'src_product_no' => (string)$item['id'],
  545. 'count' => (float)$item['num'],
  546. 'unit' => $item['xhUnitName'],
  547. ];
  548. }
  549. // 回调地址
  550. $callbackUrl = Yii::$app->params['ghsHost'] . '/delivery/dada-callback';
  551. return [
  552. 'platform' => 'dada',
  553. 'shop_no' => $shopNo,
  554. 'origin_id' => $order['orderSn'],
  555. 'cargo_price' => (float)$order['actPrice'],
  556. 'is_prepay' => 0, // 是否需要垫付 1:是 0:否 (垫付订单金额,非运费)
  557. 'receiver_name' => $order['customName'],
  558. 'receiver_address' => $order['fullAddress'],
  559. 'receiver_lat' => (float)$order['lat'],
  560. 'receiver_lng' => (float)$order['long'],
  561. 'callback' => $callbackUrl,
  562. 'cargo_weight' => isset($order['weight']) ? (float)$order['weight'] : 1.0,
  563. 'receiver_phone' => Functions::getMobile($order),
  564. //'tips' => 0, //小费(单位:元,精确小数点后一位,小费金额不能高于订单金额。)
  565. 'info' => $order['remark'] ?? '',
  566. 'product_list' => $productList,
  567. ];
  568. }
  569. /**
  570. * 准备滴滴订单数据
  571. */
  572. private function prepareDidiData($order, $shop)
  573. {
  574. return [
  575. 'platform' => 'didi',
  576. 'sender' => [
  577. 'fromSenderName' => $shop['merchantName'],
  578. 'fromMobile' => $shop['mobile'],
  579. 'fromAddress' => $shop['address'],
  580. 'fromAddressDetail' => $shop['floor'],
  581. 'fromLatitude' => (float)$shop['lat'],
  582. 'fromLongitude' => (float)$shop['long'],
  583. ],
  584. 'receiverList' => [
  585. [
  586. 'toReceiverName' => $order['customName'],
  587. 'toMobile' => Functions::getMobile($order),
  588. 'toAddress' => $order['address'],
  589. 'toAddressDetail' => $order['floor'],
  590. 'toLatitude' => (float)$order['lat'],
  591. 'toLongitude' => (float)$order['long'],
  592. 'weight' => isset($order['weight']) ? (float)$order['weight'] : 1.0,
  593. 'goodType' => 8,
  594. ]
  595. ]
  596. ];
  597. }
  598. /**
  599. * 并发获取各平台报价(核心实现)
  600. *
  601. * 使用 HttpClient::postConcurrent 实现真正的并发调用,每个平台请求 5 秒超时。
  602. * 某个平台的超时或失败不会影响其他平台的执行。
  603. *
  604. * @param array $preparedData 准备好的各平台数据
  605. * @param string $orderTime 配送时间
  606. * @return array 包含成功和失败结果
  607. */
  608. private function concurrentGetPrices($preparedData, $orderTime)
  609. {
  610. $results = [
  611. 'success' => [],
  612. 'failed' => [],
  613. ];
  614. // 第一步:收集所有平台的请求信息
  615. $allRequests = [];
  616. $platformMapping = []; // 用于将请求标识映射回平台名称
  617. foreach ($preparedData as $platform => $data) {
  618. try {
  619. $adapterKey = $platform; //由于要支持特殊逻辑处理,把 $this->adapters[xxx] 的 xxx 单独取变量
  620. if (!isset($this->adapters[$platform])) {
  621. if($platform == 'shunfeng_1v1'){ //特殊处理 -- 专人直送的订单,使用顺丰平台适配器
  622. $adapterKey = 'shunfeng';
  623. } else {
  624. $results['failed'][$platform] = '平台适配器未初始化';
  625. Yii::warning("[DispatchService] {$platform} 平台适配器未初始化");
  626. continue;
  627. }
  628. }
  629. $adapter = $this->adapters[$adapterKey];
  630. // 根据平台类型调用相应的 buildPriceRequest(s) 方法
  631. if ($platform === 'huolala') {
  632. // 货拉拉返回多个请求(一个请求对应一个车型)
  633. $priceRequests = $adapter->buildPriceRequest($data, $orderTime);
  634. foreach ($priceRequests as $requestKey => $requestInfo) {
  635. $allRequests[$requestKey] = $requestInfo;
  636. $platformMapping[$requestKey] = ['platform' => 'huolala', 'data' => $data];
  637. }
  638. } else {
  639. // 其他平台各返回一个请求
  640. $requestInfo = $adapter->buildPriceRequest($data, $orderTime);
  641. $requestKey = "{$platform}_quote";
  642. $allRequests[$requestKey] = $requestInfo;
  643. $platformMapping[$requestKey] = ['platform' => $platform, 'data' => $data];
  644. }
  645. } catch (\Throwable $e) {
  646. $results['failed'][$platform] = "构建请求失败: {$e->getMessage()}";
  647. Yii::error("[DispatchService] {$platform} 构建请求异常: {$e->getMessage()}");
  648. }
  649. }
  650. if (empty($allRequests)) {
  651. return $results;
  652. }
  653. // 第二步:使用 postConcurrent 并发发送所有请求
  654. $startTime = microtime(true);
  655. $concurrentResults = HttpClient::postConcurrent($allRequests, 3);
  656. $totalDuration = microtime(true) - $startTime;
  657. Yii::info("[DispatchService] 所有报价请求完成 (" . round($totalDuration * 1000) . "ms)");
  658. // 第三步:处理并发请求的结果
  659. foreach ($concurrentResults['success'] as $requestKey => $response) {
  660. if (!isset($platformMapping[$requestKey])) {
  661. continue;
  662. }
  663. $mapping = $platformMapping[$requestKey];
  664. $platform = $mapping['platform'];
  665. $data = $mapping['data'];
  666. try {
  667. $adapterKey = $platform; //由于要支持特殊逻辑处理,把 $this->adapters[xxx] 的 xxx 单独取变量
  668. if($platform == 'shunfeng_1v1'){ //特殊处理 -- 专人直送的订单,使用顺丰平台适配器
  669. $adapterKey = 'shunfeng';
  670. }
  671. $adapter = $this->adapters[$adapterKey];
  672. $quote = null;
  673. if ($platform === 'huolala') {
  674. // 货拉拉的响应处理
  675. $quote = $adapter->processPriceResponse($response);
  676. if ($quote && !isset($results['success']['huolala'])) {
  677. // 第一次处理货拉拉的结果,初始化
  678. $results['success']['huolala'] = [
  679. 'platform' => 'huolala',
  680. 'city_id' => $data['city_id'],
  681. 'vehicle_type_list' => $data['vehicle_type_list'],
  682. 'price_info_list' => [],
  683. ];
  684. }
  685. $keyArr = explode('_', $requestKey);
  686. $vehicle_type_list_key = $keyArr[2];
  687. // 将该车型的报价加入到列表中
  688. if ($quote && isset($results['success']['huolala'])) {
  689. $results['success']['huolala']['price_info_list'][] = [
  690. 'calculate_price_info' => isset($quote['calculate_price_info_list']) ? $quote['calculate_price_info_list'][0] : [],
  691. 'vehicle_type' => $data['vehicle_type_list'][$vehicle_type_list_key]
  692. ];
  693. Yii::info("[DispatchService] {$platform} 报价成功");// . json_encode($quote));
  694. } else {
  695. $errorMsg = $quote['error'] ?? '报价返回数据为空';
  696. $results['failed'][$platform] = $errorMsg;
  697. Yii::warning("[DispatchService] {$platform} 报价返回错误: {$errorMsg}");
  698. }
  699. } else {
  700. // 蜂鸟和闪送的响应处理
  701. $quote = $adapter->processPriceResponse($response);
  702. if ($quote && !isset($quote['error'])) {
  703. $quote['_duration'] = $totalDuration;
  704. $results['success'][$platform] = $quote;
  705. Yii::info("[DispatchService] {$platform} 报价成功");// . json_encode($quote));
  706. } else {
  707. $errorMsg = $quote['error'] ?? '报价返回数据为空';
  708. $results['failed'][$platform] = $errorMsg;
  709. Yii::warning("[DispatchService] {$platform} 报价返回错误: {$errorMsg}");
  710. if(strncmp($platform, 'shunfeng', 8) === 0) {
  711. /** @var ShunfengAdapter $adapter */
  712. if($errorMsg == '暂未开启专人直送服务') {
  713. $adapter->getShopInfo();
  714. }
  715. if($errorMsg == '当前店铺只能发独享专送') {
  716. $adapter->getShopInfo();
  717. }
  718. }
  719. }
  720. }
  721. } catch (\Throwable $e) {
  722. $results['failed'][$platform] = "处理响应失败: {$e->getMessage()}";
  723. Yii::error("[DispatchService] {$platform} 处理响应异常: {$e->getMessage()}");
  724. }
  725. }
  726. // 第四步:处理失败的请求
  727. foreach ($concurrentResults['failed'] as $requestKey => $errorMsg) {
  728. if (!isset($platformMapping[$requestKey])) {
  729. continue;
  730. }
  731. $platform = $platformMapping[$requestKey]['platform'];
  732. // 对于货拉拉,只记录某个车型失败,不影响整体平台状态
  733. if ($platform === 'huolala') {
  734. Yii::warning("[DispatchService] huolala 车型报价失败 ({$requestKey}): {$errorMsg}");
  735. } else {
  736. if (!isset($results['failed'][$platform])) {
  737. $results['failed'][$platform] = $errorMsg;
  738. Yii::error("[DispatchService] {$platform} 报价请求失败: {$errorMsg}");
  739. }
  740. }
  741. }
  742. // 为货拉拉添加元数据
  743. if (isset($results['success']['huolala'])) {
  744. $results['success']['huolala']['_duration'] = $totalDuration;
  745. }
  746. return $results;
  747. }
  748. public function openCitiesLists($platform)
  749. {
  750. $ap = $this->adapters[$platform];
  751. return $ap->cityList();
  752. }
  753. /**
  754. * 刷新 token
  755. */
  756. public function refreshToken($platform, $refreshToken, $data=[])
  757. {
  758. switch($platform) {
  759. case 'shansong':
  760. $auth = new \common\components\delivery\platform\shansong\Auth();
  761. $auth->refreshAccessToken($refreshToken);
  762. break;
  763. case 'huolala':
  764. $auth = new \common\components\delivery\platform\huolala\Auth();
  765. $auth->refreshAccessToken($refreshToken);
  766. break;
  767. case 'fengniao':
  768. $auth = new \common\components\delivery\platform\fengniao\Auth();
  769. $auth->refreshAccessToken($refreshToken, $data['merchantId']);
  770. break;
  771. case 'shunfeng':
  772. $auth = new \common\components\delivery\platform\shunfeng\Auth();
  773. $auth->refreshAccessToken($refreshToken);
  774. break;
  775. }
  776. }
  777. /**
  778. * 格式化各平台报价为前端展示格式
  779. *
  780. * @param array $platformQuotes 各平台报价结果(来自 getAllPlatformPrice)
  781. * @return array 格式化后的配送列表
  782. */
  783. public function formatPlatformQuotesForDisplay($platformQuotes)
  784. {
  785. $deliveryList = [];
  786. if (empty($platformQuotes['quotes'])) {
  787. return $deliveryList;
  788. }
  789. foreach ($platformQuotes['quotes'] as $platformKey => $item) {
  790. if(!isset($item['platform'])){
  791. Yii::error(json_encode($item));
  792. continue;
  793. }
  794. switch ($item['platform']) {
  795. case 'shunfeng':
  796. $deliveryList[] = [
  797. 'name' => '顺丰' . ($platformKey == 'shunfeng_1v1' ? ' (专送)' : ''),
  798. 'en_name' => 'shunfeng',
  799. 'price' => $item['real_pay_money'],
  800. 'distance' => $item['distance'],
  801. 'type' => '' . ($platformKey == 'shunfeng_1v1' ? '专人直送' : ''),
  802. 'isAble' => true
  803. ];
  804. break;
  805. case 'shansong':
  806. $deliveryList[] = [
  807. 'name' => '闪送',
  808. 'en_name' => 'shansong',
  809. 'price' => $item['total_amount'],
  810. 'distance' => $item['total_distance'],
  811. 'type' => '',
  812. 'issOrderNo' => $item['order_number'],
  813. 'isAble' => true
  814. ];
  815. break;
  816. case 'fengniao':
  817. // 循环遍历 goods_infos 数组,提取有效项的信息
  818. $validGoods = [];
  819. if (!empty($item['goods_infos']) && is_array($item['goods_infos'])) {
  820. foreach ($item['goods_infos'] as $good) {
  821. if (!empty($good['is_valid']) && $good['is_valid'] == 1) {
  822. $validGoods[] = [
  823. 'actual_delivery_amount_cent' => $good['actual_delivery_amount_cent'] ?? 0,
  824. 'service_goods_id' => $good['service_goods_id'] ?? ''
  825. ];
  826. $deliveryList[] = [
  827. 'name' => '蜂鸟'. ' (' .$good['base_goods_id'] . ')',
  828. 'base_goods_id' => $good['base_goods_id'],
  829. 'en_name' => 'fengniao',
  830. 'price' => $good['actual_delivery_amount_cent'],
  831. 'distance' => $item['distance'],
  832. 'valid_goods' => $validGoods,
  833. 'type' => $good['slogan'],
  834. 'isAble' => true
  835. ];
  836. } else {
  837. $deliveryList[] = [
  838. 'name' => '蜂鸟'. ' (' .$good['base_goods_id'] . ')',
  839. 'base_goods_id' => $good['base_goods_id'],
  840. 'en_name' => 'fengniao',
  841. 'price' => 0,
  842. 'distance' => $item['distance'],
  843. 'valid_goods' => $good,
  844. 'type' => $good['disable_reason'],
  845. 'isAble' => false
  846. ];
  847. }
  848. }
  849. }
  850. break;
  851. case 'huolala':
  852. foreach($item['price_info_list'] as $key => $arr) {
  853. $priceInfo = $arr['calculate_price_info'];
  854. $priceConditions = $priceInfo['price_conditions'] ?? []; //价格明细
  855. $distanceInfo = $priceInfo['distance_info'] ?? []; //距离信息
  856. $vehicleType = $arr['vehicle_type'];
  857. if(empty($priceConditions)){
  858. Yii::error('货拉拉 报价数据 priceConditions 为空:' . json_encode($item) . ' key: ' . $key);
  859. continue;
  860. }
  861. if(empty($distanceInfo)){
  862. Yii::warning('货拉拉 报价数据 distanceInfo 为空:' . json_encode($item) . ' key: ' . $key);
  863. }
  864. $priceCalculateId = $priceInfo['price_calculate_id'] ?? 0;
  865. if(!isset($priceInfo['price_calculate_id'])){
  866. Yii::warning('货拉拉 报价数据 priceInfo 缺少 price_calculate_id:' . json_encode($priceInfo) . ' key: ' . $key);
  867. }
  868. //车型信息
  869. $vehicleAttr = $priceInfo['vehicle_info']['vehicle_attr'] ?? [];
  870. if(empty($vehicleAttr)){
  871. Yii::info('货拉拉 报价数据 vehicleAttr 为空:' . ' key: ' . $key); //json_encode($priceInfo) .
  872. }
  873. $deliveryList[] = [
  874. 'name' => '货拉拉' . ' (' . $vehicleType['_meta']['vehicle_type'] . ')',
  875. 'vehicle_type' => $vehicleType['_meta']['vehicle_type'],
  876. 'en_name' => 'huolala',
  877. 'price' => !empty($priceConditions) ? $priceConditions[0]['price_info']['total_price'] : 0,
  878. 'distance' => !empty($distanceInfo) ? $distanceInfo['distance_total'] : 0,
  879. 'type' => $vehicleType['_meta']['vehicle_type'],
  880. 'isAble' => true,
  881. // ---------------------------------------------
  882. 'order_vehicle_id' => $vehicleType['order_vehicle_id'],
  883. 'city_id' => $item['city_id'],
  884. 'city_info_revision' => $vehicleType['city_info_revision'],
  885. // 下单需要透传的数据
  886. 'vehicle_std' => $vehicleType['vehicle_std'],
  887. 'spec_req' => $vehicleType['spec_req'],
  888. 'price_calculate_id' => $priceCalculateId,
  889. 'price_item_encryption' => !empty($priceConditions) ? $priceConditions[0]['price_item_encryption'] : '',
  890. 'vehicle_attr' => $vehicleAttr,
  891. 'commodity_info' => !empty($priceConditions) ? $priceConditions[0]['commodity_item'] : [],
  892. ];
  893. }
  894. break;
  895. case 'dada':
  896. $list = [
  897. 'name' => '达达',
  898. 'en_name' => 'dada',
  899. 'price' => $item['fee'],
  900. 'distance' => $item['distance'],
  901. 'type' => '',
  902. 'isAble' => true,
  903. // ---------------------------------------------
  904. 'deliverFee' => $item['deliverFee'],
  905. 'deliveryNo' => $item['deliveryNo'],
  906. ];
  907. if(isset($item['couponName']) && isset($item['couponFee'])){
  908. $list['couponName'] = $item['couponName'];
  909. $list['couponFee'] = $item['couponFee'];
  910. }
  911. $deliveryList[] = $list;
  912. break;
  913. case 'didi':
  914. if(!isset($item['estimateList'])){
  915. Yii::error('didi 报价数据为空:' . json_encode($item));
  916. continue;
  917. }
  918. $serviceType = [0 => '拼送', 1 => '直送'];
  919. foreach($item['estimateList'] as $arr) {
  920. $deliveryList[] = [
  921. 'name' => '滴滴' . ' (' . $this->adapters['didi']->carType($arr['carType']) . ')',
  922. 'en_name' => 'didi',
  923. 'price' => $arr['fee'],
  924. 'distance' => $arr['distance'],
  925. 'type' => $serviceType[$arr['serviceType']], //服务商或车型名称
  926. 'isAble' => true,
  927. // ---------------------------------------------
  928. 'estimateId' => $arr['estimateId'],
  929. 'bizType' => $arr['bizType'],
  930. 'discountFee' => $arr['discountFee'],
  931. 'icon' => $arr['icon']
  932. ];
  933. }
  934. break;
  935. }
  936. }
  937. return $deliveryList;
  938. }
  939. }