DispatchService.php 46 KB

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