DispatchService.php 43 KB

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