IntraCityController.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. <?php
  2. namespace ghs\controllers;
  3. use biz\wx\classes\WxMessageClass;
  4. use biz\wx\classes\WxOpenClass;
  5. use bizGhs\admin\classes\AdminClass;
  6. use bizGhs\express\classes\GhsExpressOrderClass;
  7. use bizGhs\shop\classes\ShopAdminClass;
  8. use bizHd\order\classes\OrderGoodsClass;
  9. use bizGhs\order\classes\OrderItemClass;
  10. use bizHd\purchase\classes\PurchaseClass;
  11. use common\components\dict;
  12. use common\components\imgUtil;
  13. use common\components\orderSn;
  14. use hd\models\IntraCity\StoreFeeForm;
  15. // 以上类来自零售端
  16. use bizGhs\order\classes\OrderClass;
  17. use biz\shop\classes\MainClass;
  18. use biz\shop\classes\ShopClass;
  19. use common\components\noticeUtil;
  20. use common\components\util;
  21. use common\components\IntraCityExpress;
  22. use yii\helpers\Json;
  23. use yii\db\Query;
  24. use Yii;
  25. /**
  26. * 同城配送控制器
  27. * 提供同城配送相关的API接口
  28. */
  29. class IntraCityController extends BaseController
  30. {
  31. public $guestAccess = ['callback'];
  32. /**
  33. * 创建门店
  34. * POST /intra-city/create-store
  35. */
  36. public function actionCreateStore()
  37. {
  38. try {
  39. $shop = $this->shop;
  40. $shopName = $shop->shopName ?? '';
  41. $sjName = $shop->merchantName ?? '';
  42. $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  43. $storeData = [
  44. 'out_store_id' => $this->mainId, //自定义门店编号
  45. 'store_name' => $name,
  46. 'address_info' => [
  47. 'province' => $shop->province,
  48. 'city' => $shop->city,
  49. 'area' => $shop->dist,
  50. 'street' => '',
  51. 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
  52. 'lat' => $shop->lat,
  53. 'lng' => $shop->long,
  54. 'phone' => $shop->telephone
  55. ]
  56. ];
  57. // 验证必填参数
  58. $requiredFields = ['out_store_id', 'store_name', 'address_info'];
  59. foreach ($requiredFields as $field) {
  60. if (empty($storeData[$field])) {
  61. util::fail("缺少必填参数:{$field}");
  62. }
  63. }
  64. // 创建门店前,检查是否已经 开通门店权限 (有wxStoreId,即说明开通了)
  65. $main = MainClass::getById($this->mainId, true, 'id, wxStoreId');
  66. // 查询是否存在 wx_store_id,不存在则执行apply
  67. if ($main->wxStoreId == '') {
  68. $re = IntraCityExpress::applyStore();
  69. if (!is_array($re)) {
  70. $re = Json::decode($re, true);
  71. }
  72. if ($re['errcode'] != 0) {
  73. Yii::error("开通门店权限失败:" . $re['errmsg']);
  74. util::fail('开通门店权限失败');
  75. }
  76. }
  77. $result = IntraCityExpress::createStore($storeData);
  78. if ($result['errcode'] === 0) {
  79. // 保存微信门店编号(wx_store_id)
  80. $main->wxStoreId = $result['wx_store_id'];
  81. $main->save();
  82. util::success($result, "门店创建成功");
  83. } else {
  84. Yii::error("门店创建失败:" . $result['errmsg']);
  85. util::fail($result['errmsg']);
  86. }
  87. } catch (\Exception $e) {
  88. Yii::error("门店创建失败:" . $e->getMessage());
  89. util::fail("系统出错");
  90. }
  91. }
  92. /**
  93. * 查询门店创建情况
  94. */
  95. public function actionStore()
  96. {
  97. $shopId = $this->shopId;
  98. // 首先从门店扩展表查询是否已经创建
  99. $main = MainClass::getById($this->mainId, true, 'id, wxStoreId');
  100. if ($main->wxStoreId == '') { // 不存在,则从微信接口查询
  101. $result = IntraCityExpress::getStore($this->mainId);
  102. if ($result['errcode'] === 0) {
  103. $store = $result['store_list'][0];
  104. // 保存 wx_store_id
  105. $main->wxStoreId = $store['wx_store_id'];
  106. $main->save();
  107. util::success($store, "门店查询成功");
  108. } else {
  109. Yii::error("门店查询失败:" . $result['errmsg']);
  110. util::error(-1, '门店查询失败');
  111. }
  112. } else {
  113. $field = 'province, city, dist, lat, long, floor, address';
  114. $shop = ShopClass::getById($shopId, false, $field);
  115. $data = array_merge($shop, $main->toArray());
  116. util::success($data, "门店查询成功");
  117. }
  118. }
  119. /**
  120. * 更新门店
  121. */
  122. public function actionUpdateStore()
  123. {
  124. // 首先从门店扩展表查询是否已经创建
  125. $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  126. if ($main['wxStoreId'] == '') {
  127. util::fail('未创建门店,请先创建');
  128. }
  129. $shop = $this->shop;
  130. $shopName = $shop->shopName ?? '';
  131. $sjName = $shop->merchantName ?? '';
  132. $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  133. $storeData = [
  134. 'keys' => ['wx_store_id' => $main['wxStoreId']],
  135. 'content' => [
  136. 'store_name' => $name,
  137. 'address_info' => [
  138. 'province' => $shop->province,
  139. 'city' => $shop->city,
  140. 'area' => $shop->dist,
  141. 'street' => '',
  142. 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
  143. 'lat' => $shop->lat,
  144. 'lng' => $shop->long,
  145. 'phone' => $shop->telephone
  146. ],
  147. //"order_pattern" => 2,
  148. //"service_trans_prefer" => "SFTC" //order_pattern = 2时必填
  149. ]
  150. ];
  151. $result = IntraCityExpress::updateStore($storeData);
  152. if ($result['errcode'] === 0) {
  153. util::success($result, "门店更新成功");
  154. } else {
  155. Yii::error("门店更新失败:" . $result['errmsg']);
  156. util::fail($result['errmsg']);
  157. }
  158. }
  159. /**
  160. * 门店运费充值
  161. */
  162. public function actionStoreCharge()
  163. {
  164. $post = Yii::$app->request->post();
  165. $amount = floatval($post['amount']);
  166. $amountTurnFen = $amount * 100;
  167. if ($amountTurnFen < 5000) {
  168. util::fail('50元起充');
  169. }
  170. $expressId = $post['expressId'];
  171. $serviceTransIds = ['SFTC', 'DADA'];
  172. if (!in_array($expressId, $serviceTransIds)) {
  173. util::fail('快递动力ID出错');
  174. }
  175. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  176. if ($shopExt['wxStoreId'] == '') {
  177. util::fail('微信门店编号为空');
  178. }
  179. $wxStoreId = $shopExt['wxStoreId'];
  180. $result = IntraCityExpress::storeCharge($wxStoreId, $expressId, $amountTurnFen);
  181. if ($result['errcode'] === 0) {
  182. util::success($result, "门店余额充值单已生成");
  183. } else {
  184. Yii::error("门店余额充值失败:" . $result['errmsg']);
  185. util::fail('门店余额充值失败');
  186. }
  187. }
  188. /**
  189. * 门店余额查询
  190. */
  191. public function actionStoreBalance()
  192. {
  193. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  194. if ($shopExt['wxStoreId'] == '') {
  195. util::error(-1, '微信门店编号为空');
  196. }
  197. $wxStoreId = $shopExt['wxStoreId'];
  198. $result = IntraCityExpress::getBalance($wxStoreId);
  199. if ($result['errcode'] === 0) {
  200. $data = ['all_balance' => $result['all_balance'] / 100.0];
  201. foreach ($result['balance_detail'] as $item) {
  202. if ($item['service_trans_id'] == 'DADA') {
  203. $data['dada_balance'] = $item['balance'] / 100.0;
  204. }
  205. if ($item['service_trans_id'] == 'SFTC') {
  206. $data['sf_balance'] = $item['balance'] / 100.0;
  207. }
  208. }
  209. util::success($data, "门店余额查询成功");
  210. } else {
  211. Yii::error("门店余额查询失败:" . $result['errmsg']);
  212. util::fail('门店余额查询失败');
  213. }
  214. }
  215. /**
  216. * 查询运费
  217. */
  218. public function actionStoreFee()
  219. {
  220. $post = Yii::$app->request->post();
  221. // 创建表单验证模型
  222. $form = new StoreFeeForm();
  223. $form->setScenario('store_fee');
  224. $form->load($post, ''); // 直接从 post 数据加载,不使用模型名作为前缀
  225. // 执行表单验证
  226. $form->validateForm();
  227. $orderId = $post['orderId'];
  228. $order = OrderClass::getById($orderId);
  229. if (empty($order)) {
  230. util::fail('订单出错');
  231. }
  232. if ($order['mainId'] != $this->mainId) {
  233. util::fail('订单出错');
  234. }
  235. $sn = $order['orderSn'];
  236. $shopId = intval($this->shopId);
  237. if (empty($shopId)) {
  238. util::fail("门店不存在");
  239. }
  240. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  241. if (empty($shopExt)) {
  242. util::fail("微信门店不存在");
  243. }
  244. $itemInfoList = OrderItemClass::getAllByCondition(['orderSn' => $sn], null, 'id, name, cover, num');
  245. $orderType = 2; // 默认是 2。说明:1花束订单 2花材订单 3花束和花材都有
  246. if (empty($itemInfoList)) {
  247. $orderType = 1;
  248. }
  249. $cargoName = '花材'; // 商品名称,默认是花材
  250. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  251. if (count($goodsInfoList) == 1) {
  252. $goodsInfo = $goodsInfoList[0];
  253. $cargoName = $goodsInfo['name'];
  254. } else {
  255. if ($orderType != 2) {
  256. util::fail("订单商品数量不正确");
  257. }
  258. }
  259. $cargo = [
  260. 'cargo_name' => $cargoName, // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  261. 'cargo_weight' => intval($post['weight'] * 1000), // 单位:克 -- 把千克转换为克
  262. 'cargo_price' => intval($post['price'] * 100), // 单位:分 -- 把元转换为分
  263. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  264. 'cargo_num' => intval($post['packageNum'])
  265. ];
  266. $originalLng = doubleval($post['user_lng']);
  267. $originalLat = doubleval($post['user_lat']);
  268. $orderData = [
  269. //'out_store_id' => $shopId,
  270. 'wx_store_id' => $shopExt['wxStoreId'],
  271. 'user_name' => $post['user_name'],
  272. 'user_phone' => $post['user_phone'],
  273. 'user_lng' => $originalLng,
  274. 'user_lat' => $originalLat,
  275. 'user_address' => $post['user_address'],
  276. 'cargo' => $cargo,
  277. 'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1, // 开发环境默认使用沙箱
  278. ];
  279. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  280. $result = IntraCityExpress::preAddOrder($orderData);
  281. if ($result['errcode'] === 0) {
  282. util::success($result, "查询成功");
  283. } else {
  284. Yii::error("运费查询失败:" . json_encode($result));
  285. util::fail('运费查询失败,编号56698');
  286. }
  287. }
  288. //根据订单查询运费 ssh
  289. public function actionGetOrderFee()
  290. {
  291. $post = Yii::$app->request->post();
  292. $orderId = $post['id'];
  293. $order = OrderClass::getById($orderId, true);
  294. if (empty($order)) {
  295. util::fail('没有找到订单');
  296. }
  297. if ($order->mainId != $this->mainId) {
  298. util::fail('不是你的订单');
  299. }
  300. $main = $this->main;
  301. $wxStoreId = $main->wxStoreId ?? '';
  302. if (empty($wxStoreId)) {
  303. util::fail('你还没有开通跑腿');
  304. }
  305. $weight = $post['weight'] ?? 0;
  306. if ($weight <= 0) {
  307. util::fail('请填写重量');
  308. }
  309. $packageNum = $post['packageNum'] ?? 1;
  310. $price = $order->actPrice ?? 0;
  311. $cargo = [
  312. 'cargo_name' => '鲜花花材', // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  313. 'cargo_weight' => intval($weight * 1000), // 单位:克 -- 把千克转换为克
  314. 'cargo_price' => intval($price * 100), // 单位:分 -- 把元转换为分
  315. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  316. 'cargo_num' => intval($packageNum)
  317. ];
  318. $originalLng = $order->long;
  319. $originalLat = $order->lat;
  320. if (empty($originalLng) || empty($originalLat)) {
  321. util::fail('客户地址不完整');
  322. }
  323. $customName = $order->customName ?? '';
  324. $customMobile = $order->customMobile ?? '';
  325. if (empty($customMobile)) {
  326. util::fail('客户手机缺失');
  327. }
  328. $address = $order->address ?? '';
  329. if (empty($address)) {
  330. util::fail('客户地址缺失');
  331. }
  332. //根据环境变量判断是否使用沙盒环境
  333. $useSandBox = getenv('YII_ENV') == 'production' ? 0 : 1;
  334. $orderData = [
  335. 'wx_store_id' => $wxStoreId,
  336. 'user_name' => $customName,
  337. 'user_phone' => $customMobile,
  338. 'user_lng' => $originalLng,
  339. 'user_lat' => $originalLat,
  340. 'user_address' => $address,
  341. 'cargo' => $cargo,
  342. 'use_sandbox' => $useSandBox,
  343. ];
  344. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  345. $result = IntraCityExpress::preAddOrder($orderData);
  346. if ($result['errcode'] === 0) {
  347. util::success($result, "查询成功");
  348. } else {
  349. $errMsg = $result['errmsg'] ?? '';
  350. $errCode = $result['errcode'] ?? '';
  351. noticeUtil::push("运费查询失败了:" . $errMsg . ",编号:" . $errCode, '15280215347');
  352. util::fail('查询失败,编号8911');
  353. }
  354. }
  355. /**
  356. * 创建订单
  357. * POST /intra-city/create-order
  358. */
  359. public function actionCreateOrder()
  360. {
  361. $post = Yii::$app->request->post();
  362. $adminId = $this->adminId;
  363. util::checkRepeatCommit($adminId, 4);
  364. $orderId = intval($post['orderId']);
  365. $order = OrderClass::getById($orderId, true);
  366. if (empty($order)) {
  367. util::fail('没有找到订单');
  368. }
  369. if ($order->mainId != $this->mainId) {
  370. util::fail('不是你的订单');
  371. }
  372. $packageNum = $post['packageNum'] ?? 0;
  373. if ($packageNum <= 0) {
  374. util::fail('请填写包裹数量');
  375. }
  376. $weight = $post['weight'] ?? 0;
  377. if ($weight <= 0) {
  378. util::fail('请填写重量');
  379. }
  380. $actPrice = $order->actPrice ?? 0;
  381. if ($actPrice <= 0) {
  382. util::fail('订单没有价格,不能发跑腿');
  383. }
  384. if ($order->status != 2) {
  385. util::fail('待发货订单才能发跑腿,请刷新页面');
  386. }
  387. //如果不是没鹛跑腿和取消了,则不能再叫跑腿,有多处,关键词no_call_express
  388. $notCanCreateSendStatus = [-2, 3];
  389. if (!in_array($order->sendStatus, $notCanCreateSendStatus)) {
  390. util::fail('不能叫跑腿,请刷新页面,编号800');
  391. }
  392. $cgId = $order->purchaseId ?? 0;
  393. $cgInfo = PurchaseClass::getById($cgId, true);
  394. if (empty($cgInfo)) {
  395. util::fail('没有采购信息');
  396. }
  397. $sn = $order->orderSn;
  398. $itemInfo = OrderItemClass::getByCondition(['orderSn' => $sn], null, 'id, name, cover, num');
  399. $num = intval($order->itemNum);
  400. $itemList[] = [
  401. 'item_name' => '花材',
  402. 'item_pic_url' => imgUtil::groupImg($itemInfo['cover']) . "?x-oss-process=image/resize,m_fill,h_130,w_130",
  403. 'count' => $num,
  404. ];
  405. $main = $this->main;
  406. $wxStoreId = $main->wxStoreId ?? '';
  407. if (empty($wxStoreId)) {
  408. util::fail('你还没有开通跑腿功能');
  409. }
  410. $cgId = $order->purchaseId ?? 0;
  411. if (empty($cgId)) {
  412. util::fail('没有找到采购信息');
  413. }
  414. $miniOpenId = '';
  415. $customShopAdminId = $order->customShopAdminId ?? 0;
  416. if (!empty($customShopAdminId)) {
  417. $customStaff = ShopAdminClass::getById($customShopAdminId, true);
  418. $customStaffAdminId = $customStaff->adminId ?? '';
  419. if (!empty($customStaffAdminId)) {
  420. $customAdmin = AdminClass::getById($customStaffAdminId, true);
  421. $miniOpenId = $customAdmin->miniOpenId ?? '';
  422. }
  423. }
  424. if (empty($miniOpenId)) {
  425. $admin = $this->admin;
  426. $miniOpenId = $admin->miniOpenId ?? '';
  427. }
  428. if (empty($miniOpenId)) {
  429. util::fail('没有找到微信登录信息,无法呼叫跑腿');
  430. }
  431. $cargoName = '鲜花花材';//商品名称
  432. $cargo = [
  433. 'cargo_name' => $cargoName,
  434. 'cargo_weight' => intval($weight * 1000),
  435. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  436. 'cargo_num' => intval($packageNum),
  437. 'cargo_price' => intval($actPrice * 100), // $order 中有各个价格,请注意
  438. 'item_list' => $itemList,
  439. ];
  440. $shopId = $this->shopId;
  441. $mainId = $this->mainId;
  442. $snData = ['shopId' => $shopId, 'mainId' => $mainId];
  443. $storeOrderId = orderSn::getGhsExpressSn($snData);
  444. $sendNum = $order->sendNum ?? '';
  445. $customName = $order->customName ?? '';
  446. if (empty($customName)) {
  447. util::fail('客户名称无效');
  448. }
  449. $customMobile = $order->customMobile ?? '';
  450. if (empty($customMobile)) {
  451. util::fail('客户手机号无效');
  452. }
  453. $long = $order->long ?? '';
  454. $lat = $order->lat ?? '';
  455. if (empty($long) || empty($lat)) {
  456. util::fail('客户地址无效');
  457. }
  458. $address = $order['address'] ?? '';
  459. if (empty($address)) {
  460. util::fail('客户地址无效呢');
  461. }
  462. $callbackUrl = Yii::$app->params['ghsHost'] . '/intra-city/callback';
  463. $orderData = [
  464. 'wx_store_id' => $wxStoreId,
  465. 'store_order_id' => $storeOrderId, //同一个门店订单编号要保证唯一,相同的订单号会重入
  466. 'user_openid' => $miniOpenId,
  467. 'user_lng' => (float)$long,
  468. 'user_lat' => (float)$lat,
  469. 'user_address' => $address,
  470. 'user_name' => $customName,
  471. 'user_phone' => $customMobile,
  472. 'order_seq' => $sendNum, // 用于配送员快速寻找到匹配的商品(非必传) -- 对应 xhOrder 表的 sendNum
  473. 'verify_code_type' => 0,
  474. 'order_detail_path' => '/pagesPurchase/purDetails?id=' . $cgId,
  475. 'callback_url' => $callbackUrl, // 订单状态回调地址(非必传)
  476. 'use_sandbox' => 0,
  477. 'cargo' => $cargo
  478. ];
  479. $result = IntraCityExpress::createOrder($orderData);
  480. if (isset($result['errcode']) && $result['errcode'] === 0) {
  481. // 保存进 xhGhsExpressOrder 表
  482. $data = [
  483. 'mainId' => $this->mainId,
  484. 'shopId' => $this->shopId,
  485. 'deliveryId' => $result['service_trans_id'] ?? '',
  486. 'wxOrderId' => $result['wx_order_id'] ?? '',
  487. 'wxStoreId' => $result['wx_store_id'] ?? '',
  488. 'storeOrderId' => $result['store_order_id'] ?? '',
  489. 'orderId' => $orderId,
  490. 'transOrderId' => $result['trans_order_id'] ?? '',
  491. 'distance' => $result['distance'] ?? 0,
  492. 'fee' => $result['fee'] ?? 0,
  493. 'fetchCode' => $result['fetch_code'] ?? '',
  494. 'orderSeq' => $result['order_seq'] ?? '',
  495. 'status' => 1,//有订单可以取消
  496. 'orderStatus' => 0,//已提交申请,待确认
  497. ];
  498. GhsExpressOrderClass::add($data);
  499. $sendDistance = $data['distance'] ?? 0;
  500. $deliveryId = $data['deliveryId'] ?? '';
  501. //更新订单
  502. $order->sendDistance = $sendDistance;
  503. $order->sendStatus = -1;//已提交申请,待确认
  504. $order->deliveryId = $deliveryId;
  505. $order->sendType = 2;
  506. $order->save();
  507. $cgInfo->sendDistance = $sendDistance;
  508. $cgInfo->sendStatus = -1;//已提交申请,待确认
  509. $cgInfo->deliveryId = $deliveryId;
  510. $cgInfo->sendType = 2;
  511. $cgInfo->save();
  512. $params = [
  513. 'fhType' => 0,
  514. 'fhWl' => '',
  515. 'fhWlNo' => '',
  516. 'staffId' => 0,
  517. 'staffName' => '',
  518. ];
  519. //确认发货,花店会增加路上库存
  520. OrderClass::orderSend($order, $params);
  521. util::success(['fee' => $data['fee']], '订单创建成功');
  522. } else {
  523. noticeUtil::push("批发 -- " . $this->mainId . ",订单创建失败:" . json_encode($result));
  524. Yii::error("订单创建失败:" . ($result['errmsg'] ?? '未知错误'), 'intraCity');
  525. util::fail('提交失败,请确认余额是否充足');
  526. }
  527. }
  528. /**
  529. * 查询订单
  530. * GET /intra-city/get-order
  531. */
  532. public function actionGetOrder()
  533. {
  534. try {
  535. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  536. if (empty($shopExt)) {
  537. util::fail("微信门店不存在");
  538. }
  539. $post = Yii::$app->request->post();
  540. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  541. $orderId = $post['orderId'];
  542. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
  543. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  544. util::fail("参数不足:wx_order_id 或 (order_id + wx_store_id) 必须提供一组");
  545. }
  546. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  547. if ($order['mainId'] != $this->mainId) {
  548. util::fail('订单未找到');
  549. }
  550. // 检查是否存在重复的订单:如果存在,则使用最后一个订单的 store_order_id
  551. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  552. $query = (new Query())
  553. ->from('xhGhsExpressOrder')
  554. ->where(['orderId' => $orderId])
  555. ->andWhere(['mainId' => $this->mainId]);
  556. $esDatas = $query->all();
  557. $count = count($esDatas);
  558. if ($count > 0) {
  559. $es = $esDatas[0];
  560. $storeOrderId = $es['storeOrderId'];
  561. }
  562. $result = IntraCityExpress::queryOrder($wxStoreId, $storeOrderId, $wxOrderId);
  563. if (isset($result['errcode']) && $result['errcode'] === 0) {
  564. util::success($result, "查询成功");
  565. } else {
  566. Yii::error("订单查询失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  567. util::fail('订单查询失败: ' . $result['errcode']);
  568. }
  569. } catch (\Exception $e) {
  570. Yii::error("订单查询异常:" . $e->getMessage(), 'intracity');
  571. util::fail("系统出错");
  572. }
  573. }
  574. /**
  575. * 取消订单
  576. * POST /intra-city/cancel-order
  577. */
  578. public function actionCancelOrder()
  579. {
  580. try {
  581. $post = Yii::$app->request->post();
  582. $adminId = $this->adminId;
  583. util::checkRepeatCommit($adminId, 4);
  584. $orderId = $post['orderId'] ?? 0;
  585. $order = OrderClass::getById($orderId, true);//todo 这时必须取全部字段,下面发货要用到,否则会出错,请勿修改
  586. if (empty($order)) {
  587. util::fail('没有找到订单');
  588. }
  589. if ($order->mainId != $this->mainId) {
  590. util::fail('不是你的订单');
  591. }
  592. if ($order->status != 3) {
  593. util::fail('不能取消');
  594. }
  595. if (in_array($order->sendStatus, [-1, 2, 3])) {
  596. //订单 没叫跑腿、已送达、已取消
  597. util::fail('不能取消哈');
  598. }
  599. $cgId = $order->purchaseId ?? 0;
  600. $cg = PurchaseClass::getById($cgId, true);
  601. if (empty($cg)) {
  602. util::fail('没有采购单信息');
  603. }
  604. $main = $this->main;
  605. $wxStoreId = $main->wxStoreId ?? '';
  606. $express = GhsExpressOrderClass::getByCondition(['orderId' => $orderId, 'status' => 1], true);
  607. if (empty($express)) {
  608. util::fail('没有找到有效配送单');
  609. }
  610. $wxOrderId = $express->wxOrderId ?? '';
  611. $storeOrderId = $express->storeOrderId ?? '';
  612. $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
  613. if (isset($result['errcode']) && $result['errcode'] === 0) {
  614. // 更新订单状态
  615. $order->sendStatus = 3;
  616. $order->save();
  617. $cg->sendStatus = 3;
  618. $cg->save();
  619. $params = ['staffId' => 0, 'staffName' => ''];
  620. OrderClass::cancelOrderSend($order, $params);
  621. $deductFee = $result['deductfee'] ?? 0;
  622. $express->status = 0;
  623. $express->cancelTime = date('Y-m-d H:i:s');
  624. $express->deductfee = $deductFee;
  625. $express->save();
  626. util::success($result, "订单取消成功");
  627. } else {
  628. Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  629. util::fail('取消失败,编号6693');
  630. }
  631. } catch (\Exception $e) {
  632. Yii::error("订单取消异常:" . $e->getMessage(), 'intraCity');
  633. util::fail("系统出错");
  634. }
  635. }
  636. /**
  637. * 微信回调接口
  638. */
  639. public function actionCallback()
  640. {
  641. $callbackData = Yii::$app->request->post();
  642. if (empty($callbackData)) {
  643. $postStr = file_get_contents('php://input');
  644. $callbackData = json_decode($postStr, true);
  645. if (empty($callbackData)) {
  646. util::fail('回调请求的数据为空');
  647. }
  648. }
  649. // 从配置中获取安全token
  650. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  651. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  652. // 记录回调日志
  653. Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'intraCity');
  654. $storeOrderId = $callbackData['store_order_id'] ?? 0;
  655. $wxStoreId = $callbackData['wx_store_id'] ?? ''; //微信门店编号
  656. if (empty($storeOrderId) || empty($wxStoreId)) {
  657. Yii::error("配送单回调接口的请求参数出错,storeOrderId = $storeOrderId, wxStoreId = $wxStoreId");
  658. return $this->asJson(['return_code' => 1, 'return_msg' => '请求参数不正确']);
  659. }
  660. try {
  661. // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
  662. $eo = GhsExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
  663. if (empty($eo)) {
  664. Yii::error('订单不存在. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  665. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  666. }
  667. $orderId = $eo->orderId ?? 0;
  668. if (empty($orderId)) {
  669. $errRemind = '订单号为空,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  670. Yii::error($errRemind, 'intracity');
  671. noticeUtil::push($errRemind, '15280215347');
  672. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误2']);
  673. }
  674. $order = OrderClass::getById($orderId, true);//todo 注意,这里必须取全部字段,否则下面发错会出错!!!!!!!!
  675. if (empty($order)) {
  676. $errRemind = '没有找到订单,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  677. Yii::error($errRemind, 'intracity');
  678. noticeUtil::push($errRemind, '15280215347');
  679. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误3']);
  680. }
  681. $cgId = $order->purchaseId ?? 0;
  682. $cg = PurchaseClass::getById($cgId, true);
  683. if (empty($cg)) {
  684. $errRemind = '没有找到采购单,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  685. Yii::error($errRemind, 'intracity');
  686. noticeUtil::push($errRemind, '15280215347');
  687. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误4']);
  688. }
  689. $orderStatus = intval($callbackData['order_status']);
  690. //同个配送单,同个状态的,5秒内不允许重复请求,重要勿删
  691. $uniqueId = $storeOrderId . '_' . $orderStatus;
  692. util::checkRepeatCommit($uniqueId, 5);
  693. // ====================== 开启事务
  694. $tx = Yii::$app->db->beginTransaction();
  695. $msg = ''; // 发通知的内容(默认为空,根据情况生成。没有内容则不会发通知)
  696. switch ($orderStatus) {
  697. // 订单创建成功,已叫跑腿,等跑腿接单
  698. case IntraCityExpress::ORDER_STATUS_CREATED:
  699. if ($order->status == 3) {
  700. $eo->orderStatus = 1;//已叫跑腿,等跑腿接单
  701. $eo->save();
  702. $order->sendStatus = 0;//已叫跑腿,等跑腿接单
  703. $order->save();
  704. $cg->sendStatus = 0;//已叫跑腿,等跑腿接单
  705. $cg->save();
  706. }
  707. break;
  708. // 配送员接单
  709. case IntraCityExpress::ORDER_STATUS_ACCEPTED:
  710. if ($order->status == 3) {
  711. $eo->orderStatus = 4;//跑腿已接单
  712. $eo->save();
  713. $order->sendStatus = 1;//跑腿已接单
  714. $order->save();
  715. $cg->sendStatus = 1;//跑腿已接单
  716. $cg->save();
  717. }
  718. break;
  719. // 配送员到店
  720. case IntraCityExpress::ORDER_STATUS_ARRIVED:
  721. if ($order->status == 3) {
  722. $eo->orderStatus = 5;//跑腿到店
  723. $eo->save();
  724. $order->sendStatus = 4;//跑腿到店
  725. $order->save();
  726. $cg->sendStatus = 4;//跑腿到店
  727. $cg->save();
  728. }
  729. break;
  730. // 配送中
  731. case IntraCityExpress::ORDER_STATUS_DELIVERING:
  732. if ($order->status == 3) {
  733. $eo->orderStatus = 6;//跑腿配送中
  734. $eo->save();
  735. $order->sendStatus = 5;//跑腿配送中
  736. $order->save();
  737. $cg->sendStatus = 5;//跑腿配送中
  738. $cg->save();
  739. }
  740. break;
  741. // 配送完成
  742. case IntraCityExpress::ORDER_STATUS_COMPLETED:
  743. if ($order->status == 3) {
  744. $eo->orderStatus = 8;//配送完成
  745. $eo->save();
  746. $order->sendStatus = 2;//已送达
  747. $order->save();
  748. $cg->sendStatus = 2;//已送达
  749. $cg->save();
  750. $params = ['staffId' => 0, 'staffName' => ''];
  751. OrderClass::confirmReach($order, $params);
  752. }
  753. break;
  754. // 商家取消订单
  755. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
  756. //取消已发货,回滚到待发货
  757. if ($order->status == 3) {
  758. $eo->orderStatus = 2;
  759. $eo->save();
  760. $order->sendStatus = 3;
  761. $order->save();
  762. $cg->sendStatus = 3;
  763. $cg->save();
  764. $params = ['staffId' => 0, 'staffName' => ''];
  765. OrderClass::cancelOrderSend($order, $params);
  766. }
  767. $msg = '取消配送,订单编号 ';
  768. break;
  769. // 配送方取消订单
  770. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_DELIVERY:
  771. //取消已发货,回滚到待发货
  772. if ($order->status == 3) {
  773. $eo->orderStatus = 3;
  774. $eo->status = 0;
  775. $eo->save();
  776. $order->sendStatus = 3;
  777. $order->save();
  778. $cg->sendStatus = 3;
  779. $cg->save();
  780. $params = ['staffId' => 0, 'staffName' => ''];
  781. OrderClass::cancelOrderSend($order, $params);
  782. }
  783. $msg = '配送方取消配送,订单编号 ';
  784. break;
  785. // 配送员撤单
  786. case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
  787. //todo 配送员撤单,目前我们认为会重新派单,先不要有任何操作!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  788. $msg = '跑腿取消配送,订单编号 ';
  789. break;
  790. // 配送异常
  791. case IntraCityExpress::ORDER_STATUS_EXCEPTION:
  792. //取消已发货,回滚到待发货
  793. if ($order->status == 3) {
  794. $eo->orderStatus = 9;
  795. $eo->status = 0;
  796. $eo->save();
  797. $order->sendStatus = 3;
  798. $order->save();
  799. $cg->sendStatus = 3;
  800. $cg->save();
  801. $params = ['staffId' => 0, 'staffName' => ''];
  802. OrderClass::cancelOrderSend($order, $params);
  803. }
  804. $msg = '订单配送异常,订单编号 ';
  805. break;
  806. }
  807. // ====================== 事务提交
  808. $tx->commit();
  809. if (!empty($msg)) {
  810. $order = OrderClass::getById($orderId, true, 'id, shopId, customName, sendNum');
  811. $shop = ShopClass::getById($order->shopId, true, 'id, ptStyle, mainId');
  812. $result = $msg . $order->sendNum;
  813. WxMessageClass::expressErrorInform($shop, $order->customName, $orderId, $result);
  814. }
  815. // 成功状态的返回数据
  816. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  817. } catch (\Exception $e) {
  818. Yii::error('同城配送回调处理异常:' . $e->getMessage());
  819. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  820. }
  821. }
  822. //模拟接口回调 ssh 20250826
  823. public function actionMockNotify()
  824. {
  825. if (getenv('YII_ENV') != 'production') {
  826. $post = Yii::$app->request->post();
  827. $orderStatus = $post['orderStatus'] ?? 0;
  828. $wxOrderId = $post['wxOrderId'] ?? '';
  829. $ptStyle = dict::getDict('ptStyle', 'hd');
  830. $merchant = WxOpenClass::getWxInfo();
  831. $ret = IntraCityExpress::mockNotify($orderStatus, $wxOrderId, '', '', $merchant, $ptStyle);
  832. util::success($ret);
  833. }
  834. util::complete();
  835. }
  836. }