DispatchService.php 45 KB

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