DispatchService.php 44 KB

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