OrderController.php 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  1. <?php
  2. namespace hd\controllers;
  3. use bizHd\hb\classes\HbClass;
  4. use bizHd\hb\classes\HbScopeClass;
  5. use Yii;
  6. use biz\shop\classes\ShopExtClass;
  7. use biz\sj\services\MerchantExtendService;
  8. use biz\sj\services\MerchantService;
  9. use bizHd\custom\classes\CustomClass;
  10. use bizHd\custom\classes\HdClass;
  11. use bizHd\distribution\classes\DistributionCommissionClass;
  12. use bizHd\goods\classes\GoodsClass;
  13. use bizHd\merchant\services\ShopService;
  14. use bizHd\order\classes\OrderClass;
  15. use bizHd\order\classes\OrderForwardClass;
  16. use bizHd\order\classes\OrderItemClass;
  17. use bizHd\order\classes\OrderSendClass;
  18. use hd\models\order\CreateOrderForm;
  19. use bizHd\express\classes\HdDeliveryOrderClass;
  20. use bizHd\order\services\OrderService;
  21. use bizHd\product\classes\ProductClass;
  22. use bizHd\saas\services\RegionService;
  23. use bizHd\shop\classes\ShopClass;
  24. use bizHd\user\services\UserService;
  25. use bizHd\work\classes\WorkClass;
  26. use common\components\dict;
  27. use common\components\dateUtil;
  28. use common\components\noticeUtil;
  29. use common\components\orderSn;
  30. use common\components\payUtil;
  31. use common\services\xhPayToolService;
  32. use common\components\util;
  33. use common\components\stringUtil;
  34. use bizHd\promote\services\CouponService;
  35. use common\components\httpUtil;
  36. use biz\wx\classes\WxMessageClass;
  37. use common\components\lakala\Lakala;
  38. use yii\helpers\ArrayHelper;
  39. class OrderController extends BaseController
  40. {
  41. public $guestAccess = ['order-relate', 'fast-pay', 'create-order', 'list', 'info'];
  42. public function actionDebt()
  43. {
  44. $get = Yii::$app->request->get();
  45. $id = $get['id'] ?? 0;
  46. $info = OrderClass::getById($id, true);
  47. if (empty($info)) {
  48. util::fail('没有找到订单');
  49. }
  50. if ($info->mainId != $this->mainId) {
  51. util::fail('不是你的订单');
  52. }
  53. //4秒内不允许重复提交
  54. util::checkRepeatCommit($id, 4);
  55. if ($info->status != 1) {
  56. util::fail('订单已付款或取消');
  57. }
  58. $payWay = dict::getDict('payWay', 'debtPay');
  59. $connection = Yii::$app->db;
  60. $transaction = $connection->beginTransaction();
  61. try {
  62. $actPrice = $info->actPrice ?? 0;
  63. $info->debtPrice = $actPrice;
  64. $info->remainDebtPrice = $actPrice;
  65. $info->debt = 1;
  66. $info->save();
  67. OrderClass::payAfter($info, $payWay);
  68. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  69. if ($info->getGoods == 1 && $info->sendType == 1 && $info->status == 2) {
  70. $info->status = 4;
  71. $info->save();
  72. DistributionCommissionClass::onRetailOrderCompleted((int)$info->id);
  73. }
  74. $transaction->commit();
  75. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  76. HdDeliveryOrderClass::payAfter($info);
  77. util::complete('赊账成功');
  78. } catch (\Exception $exception) {
  79. $transaction->rollBack();
  80. Yii::info("赊账失败原因:" . $exception->getMessage());
  81. util::fail('操作失败');
  82. }
  83. }
  84. //取消订单 ssh 20221231
  85. public function actionCancel()
  86. {
  87. $shopAdmin = $this->shopAdmin;
  88. //避免重复提交
  89. $adminId = $this->adminId;
  90. util::checkRepeatCommit($adminId, 3);
  91. $get = Yii::$app->request->get();
  92. $cashier = $get['cashier'] ?? 0;
  93. //是否强制取消订单 0不要强制 1强制,没有关单成功也要取消
  94. $forceCancel = $get['forceCancel'] ?? 0;
  95. $id = $get['id'] ?? 0;
  96. $order = OrderClass::getById($id, true);
  97. if ($order->mainId != $this->mainId) {
  98. util::fail('不是你的订单');
  99. }
  100. //如果收银台的订单,取消时要关闭拉卡拉的订单
  101. if ($cashier == 1) {
  102. //已取消,不需要再走下面的流程
  103. if ($order->status == 5) {
  104. util::complete('已取消');
  105. }
  106. $orderSn = $order->orderSn ?? '';
  107. $shop = $this->shop;
  108. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  109. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  110. $params = [
  111. 'appid' => 'OP00002119',
  112. 'serial_no' => '018b08cfddbd',
  113. 'merchant_no' => $shop->lklSjNo,
  114. 'term_no' => $shop->lklScanTermNo,
  115. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  116. 'lklCertificatePath' => $lklCertificatePath,
  117. ];
  118. $laResource = new Lakala($params);
  119. // 1. 先查询拉卡拉侧订单状态
  120. $queryResponse = $laResource->query(['orderSn' => $orderSn]);
  121. //响应CODE为BBS00000,仅表示查到了这笔交易。交易本身的成功与否状态,要查看响应报文中的trade_state这个值
  122. if (isset($queryResponse['code']) && $queryResponse['code'] == 'BBS00000') {
  123. $tradeState = $queryResponse['resp_data']['trade_state'] ?? '';
  124. // 订单已支付,拦截取消操作
  125. if ($tradeState == 'SUCCESS') {
  126. util::fail('已付款,不能取消');
  127. }
  128. // 根据拉卡拉聚合支付文档(id=116)及实际情况,判断是否为非终态
  129. // INIT:初始化, CREATE:下单成功, DEAL:交易处理中, USERPAYING:支付中, NOTPAY:未支付
  130. $pendingStates = ['INIT', 'CREATE', 'DEAL', 'USERPAYING', 'NOTPAY'];
  131. if (in_array($tradeState, $pendingStates)) {
  132. $closeParams = ['orderSn' => $orderSn];
  133. $closeResponse = $laResource->close($closeParams);
  134. if (!isset($closeResponse['code']) || $closeResponse['code'] != 'BBS00000') {
  135. $msg = $closeResponse['msg'] ?? '关闭失败';
  136. noticeUtil::push("拉卡拉聚合支付关单失败:{$orderSn},原因:{$msg} 原单状态:{$tradeState}", '15280215347');
  137. if ($forceCancel == 0) {
  138. //返回禁止关单
  139. util::fail('取消失败,如必要请强制取消');
  140. }
  141. }else{
  142. noticeUtil::push("关单成功,订单号:{$orderSn} 原单状态:{$tradeState}", '15280215347');
  143. }
  144. }
  145. }
  146. }
  147. $connection = Yii::$app->db;
  148. $transaction = $connection->beginTransaction();
  149. try {
  150. OrderClass::setExpire($order, true, $shopAdmin);
  151. $transaction->commit();
  152. util::complete('已取消');
  153. } catch (\Exception $exception) {
  154. $transaction->rollBack();
  155. Yii::info("取消原因:" . $exception->getMessage());
  156. util::fail('取消失败');
  157. }
  158. }
  159. //修改订单 ssh 20220926
  160. public function actionUpdate()
  161. {
  162. $post = Yii::$app->request->post();
  163. $id = $post['id'] ?? 0;
  164. $order = OrderClass::getById($id, true);
  165. OrderClass::valid($order, $this->mainId);
  166. unset($post['id']);
  167. if ($order->status == 3) {
  168. util::fail('订单已配送');
  169. }
  170. if ($order->status == 4) {
  171. util::fail('订单已完成');
  172. }
  173. if ($order->status == 5) {
  174. util::fail('订单已取消');
  175. }
  176. if ($order->fromType == 4) {
  177. util::fail('请在美团APP上修改');
  178. }
  179. $address = $post['address'] ?? '';
  180. $floor = $post['floor'] ?? '';
  181. $post['fullAddress'] = $address . $floor;
  182. OrderClass::updateById($id, $post);
  183. $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  184. $remark = $post['remark'] ?? '';
  185. $reachDate = $post['reachDate'] ?? '';
  186. $reachPeriod = $post['reachPeriod'] ?? '';
  187. $cardInfo = $post['cardInfo'] ?? '';
  188. $anonymity = $post['anonymity'] ?? 0;
  189. $bookName = $post['bookName'] ?? '';
  190. if (!empty($workList)) {
  191. foreach ($workList as $work) {
  192. $work->remark = $remark;
  193. $work->reachDate = $reachDate;
  194. $work->reachPeriod = $reachPeriod;
  195. $work->cardInfo = $cardInfo;
  196. $work->anonymity = $anonymity;
  197. $work->bookName = $bookName;
  198. $work->save();
  199. }
  200. }
  201. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  202. ShopExtClass::orderUpdateRemind($shopExt, $order);
  203. util::complete();
  204. }
  205. //客户欠款的订单 ssh 2021.2.4
  206. public function actionDebtList()
  207. {
  208. $get = Yii::$app->request->get();
  209. $id = $get['id'] ?? 0;
  210. $info = CustomClass::getById($id, true);
  211. CustomClass::valid($info, $this->shopId);
  212. $where = ['customId' => $id, 'debt' => 1];
  213. $searchTime = $get['searchTime'] ?? '';
  214. if (!empty($searchTime)) {
  215. $startTime = $get['startTime'] ?? '';
  216. $endTime = $get['endTime'] ?? '';
  217. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  218. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  219. }
  220. $allowedPageSizes = [100, 200, 300];
  221. $pageSize = isset($get['pageSize']) && in_array((int)$get['pageSize'], $allowedPageSizes, true)
  222. ? (int)$get['pageSize'] : 100;
  223. $page = max(1, (int)($get['page'] ?? 1));
  224. $fields = ['id', 'orderSn', 'actPrice', 'addTime', 'remainDebtPrice', 'debtPrice'];
  225. Yii::$app->request->setQueryParams(array_merge($get, ['page' => $page, 'pageSize' => $pageSize]));
  226. $result = OrderClass::getList($fields, $where, 'addTime DESC');
  227. if (!empty($result['list'])) {
  228. foreach ($result['list'] as $key => $value) {
  229. $debtPrice = $value['debtPrice'] ?? 0;
  230. $remainDebtPrice = $value['remainDebtPrice'] ?? 0;
  231. $hasPayDebt = 0;
  232. if ($debtPrice > $remainDebtPrice) {
  233. $hasPayDebt = bcsub($debtPrice, $remainDebtPrice, 2);
  234. }
  235. $result['list'][$key]['hasPayDebt'] = floatval($hasPayDebt);
  236. }
  237. }
  238. $result['customInfo'] = $info;
  239. util::success($result);
  240. }
  241. //确认送达 ssh 20250902
  242. public function actionReach()
  243. {
  244. //解决重复提交
  245. util::checkRepeatCommit($this->adminId, 5);
  246. $get = Yii::$app->request->get();
  247. $id = $get['id'] ?? 0;
  248. $order = OrderClass::getById($id, true);
  249. if (empty($order)) {
  250. util::fail('没有找到订单');
  251. }
  252. OrderClass::valid($order, $this->mainId);
  253. if ($order->status == 5) {
  254. util::fail('订单已取消');
  255. }
  256. if ($order->status == 1) {
  257. util::fail('订单待付款');
  258. }
  259. if ($order->status == 2) {
  260. util::fail('订单未发货');
  261. }
  262. if ($order->status == 4) {
  263. util::fail('订单已经送到了');
  264. }
  265. if (!in_array($order->sendStatus, [-1, -4])) {
  266. util::fail('由跑腿送货,无需确认');
  267. }
  268. $order->status = 4;
  269. $order->save();
  270. DistributionCommissionClass::onRetailOrderCompleted((int)$order->id);
  271. util::complete('操作成功');
  272. }
  273. //确认取货
  274. public function actionFetch()
  275. {
  276. $get = Yii::$app->request->get();
  277. $id = $get['id'] ?? 0;
  278. //解决重复提交
  279. util::checkRepeatCommit($id . '_' . $this->adminId, 5);
  280. $order = OrderClass::getById($id, true);
  281. if (empty($order)) {
  282. util::fail('没有找到订单');
  283. }
  284. OrderClass::valid($order, $this->mainId);
  285. if ($order->status == 5) {
  286. util::fail('订单已取消');
  287. }
  288. if ($order->status == 1) {
  289. util::fail('订单待付款');
  290. }
  291. if ($order->status == 4) {
  292. util::fail('订单已取过了');
  293. }
  294. if (in_array($order->sendStatus, [-1, 0, 1, 2, 4, 5])) {
  295. util::fail('由跑腿送货,无需确认');
  296. }
  297. $order->status = 4;
  298. $successTime = date('Y-m-d H:i:s');
  299. $order->successTime = $successTime;
  300. $order->save();
  301. DistributionCommissionClass::onRetailOrderCompleted((int)$order->id, $successTime);
  302. util::complete('操作成功');
  303. }
  304. //批量确认取货 待发货的自取订单 每次500个
  305. public function actionBatchFetch()
  306. {
  307. $where = ["status" => 2, "sendType" => 1, "shopId" => $this->shopId];
  308. $orderList = OrderService::getLimitList("id", $where, 500, "id desc");
  309. $ids = ArrayHelper::getColumn($orderList, "id");
  310. OrderService::updateByIds($ids, ["status" => 4]);
  311. util::complete($ids);
  312. }
  313. //确认发货
  314. public function actionSend()
  315. {
  316. //解决重复提交
  317. util::checkRepeatCommit($this->adminId, 5);
  318. $get = Yii::$app->request->get();
  319. $id = $get['id'] ?? 0;
  320. $order = OrderClass::getById($id, true);
  321. if (empty($order)) {
  322. util::fail('没有找到订单');
  323. }
  324. OrderClass::valid($order, $this->mainId);
  325. if ($order->status != 2) {
  326. util::fail('订单不是待发货状态');
  327. }
  328. // $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  329. // if (!empty($workList)) {
  330. // $unComplete = false;
  331. // foreach ($workList as $work) {
  332. // if ($work->status != 1) {
  333. // $unComplete = true;
  334. // }
  335. // }
  336. // if ($unComplete == true) {
  337. // util::fail('还有制作单没有完成');
  338. // }
  339. // }
  340. $order->status = 3;
  341. $order->save();
  342. util::complete('已发货');
  343. }
  344. //打印订单 ssh 20220601
  345. public function actionPrintOrder()
  346. {
  347. $get = Yii::$app->request->get();
  348. $id = isset($get['id']) ? $get['id'] : 0;
  349. $order = OrderClass::getById($id, true);
  350. if (empty($order)) {
  351. util::fail('没有找到订单');
  352. }
  353. if ($order->forward == 1) {
  354. util::fail('红冲订单不能打印');
  355. }
  356. OrderClass::valid($order, $this->mainId);
  357. OrderClass::onlinePrint($order, true);
  358. util::complete();
  359. }
  360. //微信和支付宝付款码支付复查 ssh 20220422
  361. public function actionCodePayCheck()
  362. {
  363. ini_set('date.timezone', 'Asia/Shanghai');
  364. header("Content-type: text/html; charset=utf-8");
  365. $get = Yii::$app->request->get();
  366. $id = isset($get['id']) ? $get['id'] : 0;
  367. util::checkRepeatCommit($id, 3);
  368. $order = OrderClass::getById($id, true);
  369. OrderClass::valid($order, $this->mainId);
  370. $orderSn = $order->orderSn ?? '';
  371. $totalFee = $order->mainPay ?? 0;
  372. if ($order->payStatus == 1) {
  373. util::success(['returnStatus' => 'SUCCESS']);
  374. }
  375. if ($order->status == 5) {
  376. util::success(['returnStatus' => 'CANCEL']);
  377. }
  378. $connection = Yii::$app->db;
  379. $transaction = $connection->beginTransaction();
  380. try {
  381. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  382. $shop = $this->shop;
  383. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  384. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  385. $params = [
  386. 'appid' => 'OP00002119',
  387. 'serial_no' => '018b08cfddbd',
  388. 'merchant_no' => $shop->lklSjNo,
  389. 'term_no' => $shop->lklScanTermNo,
  390. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  391. 'lklCertificatePath' => $lklCertificatePath,
  392. ];
  393. $laResource = new Lakala($params);
  394. $scanParams = ['orderSn' => $orderSn,];
  395. $response = $laResource->query($scanParams);
  396. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  397. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  398. $payWayType = dict::getDict('payWay', 'wxPay');
  399. $account_type = $response['resp_data']['account_type'] ?? '';
  400. if ($account_type == 'WECHAT') {
  401. $payWayType = dict::getDict('payWay', 'wxPay');
  402. }
  403. if ($account_type == 'ALIPAY') {
  404. $payWayType = dict::getDict('payWay', 'alipay');
  405. }
  406. $transactionId = $response['resp_data']['trade_no'] ?? '';
  407. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  408. $order->save();
  409. $attach = '';
  410. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  411. $transaction->commit();
  412. //解决重复通知
  413. $cacheKey = 'pay_success_notice_' . $orderSn;
  414. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  415. if (empty($has)) {
  416. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  417. //打印小票和语音播报
  418. $newOrder = OrderClass::getById($id, true);
  419. OrderClass::onlinePrint($newOrder);
  420. ShopExtClass::hdGatheringReport($newOrder);
  421. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  422. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  423. $newOrder->status = 4;
  424. $newOrder->save();
  425. }
  426. HdDeliveryOrderClass::payAfter($newOrder);
  427. $shopId = $newOrder->shopId ?? 0;
  428. $shop = ShopClass::getById($shopId, true);
  429. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  430. }
  431. util::success(['returnStatus' => 'SUCCESS']);
  432. } else {
  433. util::complete('未知状态..');
  434. }
  435. }
  436. util::complete('未知状态..');
  437. } catch (\Exception $e) {
  438. $transaction->rollBack();
  439. util::complete('支付失败');
  440. }
  441. }
  442. //微信和支付宝付款码支付复查 ssh 20260716
  443. public function actionCodePayVerify()
  444. {
  445. ini_set('date.timezone', 'Asia/Shanghai');
  446. header("Content-type: text/html; charset=utf-8");
  447. $get = Yii::$app->request->get();
  448. $id = $get['id'] ?? 0;
  449. util::checkRepeatCommit($id, 3);
  450. $order = OrderClass::getById($id, true);
  451. OrderClass::valid($order, $this->mainId);
  452. $orderSn = $order->orderSn ?? '';
  453. $totalFee = $order->mainPay ?? 0;
  454. if ($order->payStatus == 1) {
  455. util::success(['returnStatus' => 'SUCCESS']);
  456. }
  457. if ($order->status == 5) {
  458. util::success(['returnStatus' => 'CANCEL']);
  459. }
  460. $connection = Yii::$app->db;
  461. $transaction = $connection->beginTransaction();
  462. try {
  463. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  464. $shop = $this->shop;
  465. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  466. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  467. $params = [
  468. 'appid' => 'OP00002119',
  469. 'serial_no' => '018b08cfddbd',
  470. 'merchant_no' => $shop->lklSjNo,
  471. 'term_no' => $shop->lklScanTermNo,
  472. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  473. 'lklCertificatePath' => $lklCertificatePath,
  474. ];
  475. $laResource = new Lakala($params);
  476. $scanParams = ['orderSn' => $orderSn,];
  477. $response = $laResource->query($scanParams);
  478. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  479. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  480. $payWayType = dict::getDict('payWay', 'wxPay');
  481. $account_type = $response['resp_data']['account_type'] ?? '';
  482. if ($account_type == 'WECHAT') {
  483. $payWayType = dict::getDict('payWay', 'wxPay');
  484. }
  485. if ($account_type == 'ALIPAY') {
  486. $payWayType = dict::getDict('payWay', 'alipay');
  487. }
  488. $transactionId = $response['resp_data']['trade_no'] ?? '';
  489. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  490. $order->save();
  491. $attach = '';
  492. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  493. $transaction->commit();
  494. //解决重复通知
  495. $cacheKey = 'pay_success_notice_' . $orderSn;
  496. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  497. if (empty($has)) {
  498. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  499. //打印小票和语音播报
  500. $newOrder = OrderClass::getById($id, true);
  501. OrderClass::onlinePrint($newOrder);
  502. ShopExtClass::hdGatheringReport($newOrder);
  503. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  504. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  505. $newOrder->status = 4;
  506. $newOrder->save();
  507. }
  508. HdDeliveryOrderClass::payAfter($newOrder);
  509. $shopId = $newOrder->shopId ?? 0;
  510. $shop = ShopClass::getById($shopId, true);
  511. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  512. }
  513. util::success(['returnStatus' => 'SUCCESS']);
  514. } else {
  515. util::success(['returnStatus' => 'PENDING'], '等待支付中...');
  516. }
  517. }
  518. util::success(['returnStatus' => 'PENDING'], '等待支付中...');
  519. } catch (\Exception $e) {
  520. $transaction->rollBack();
  521. util::complete('支付失败');
  522. }
  523. }
  524. /**
  525. * 微信和支付宝付款码支付
  526. * 职责:处理商户扫描客户付款码(被扫支付)的请求,调用拉卡拉支付接口并更新本地订单状态(零售端)
  527. * 入参:GET 传参 id (订单ID), authCode (付款码), version (版本号)
  528. * 返回:JSON 格式的支付结果(SUCCESS/FAILURE)
  529. * 副作用:更新订单支付状态、支付方式,记录支付日志,触发云打印、跑腿呼叫及语音播报
  530. * 关键边界:
  531. * 1. 验证订单有效性与待付款状态
  532. * 2. 校验付款码格式(微信/支付宝)
  533. * 3. 优化:将拉卡拉外部网络请求移出数据库事务,避免因网络延迟长时间占用数据库连接和行锁
  534. */
  535. public function actionCodePay()
  536. {
  537. ini_set('date.timezone', 'Asia/Shanghai');
  538. header("Content-type: text/html; charset=utf-8");
  539. $get = Yii::$app->request->get();
  540. $id = isset($get['id']) ? $get['id'] : 0;
  541. util::checkRepeatCommit($id, 3);
  542. $version = $get['version'] ?? 0;
  543. $order = OrderClass::getById($id, true);
  544. OrderClass::valid($order, $this->mainId);
  545. if ($order->status == OrderClass::ORDER_STATUS_CANCEL) {
  546. $msg = '订单已取消';
  547. util::success(['returnStatus' => 'FAILURE'], $msg);
  548. }
  549. if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
  550. $msg = '订单不是待付款状态';
  551. util::success(['returnStatus' => 'FAILURE'], $msg);
  552. }
  553. $shop = $this->shop;
  554. $sj = $shop->merchantName;
  555. $shopName = $shop->shopName;
  556. $name = $shopName == '首店' ? $sj : $sj . '-' . $shopName;
  557. $authCode = (string)$get['authCode'] ?? '';
  558. if ($version > 0) {
  559. if (empty($authCode)) {
  560. $msg = '没有扫到付款码';
  561. $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  562. noticeUtil::push($remind . ' 编号005', '15280215347');
  563. util::success(['returnStatus' => 'FAILURE'], $msg);
  564. }
  565. //微信文档说明 https://pay.weixin.qq.com/doc/v2/merchant/4011936234
  566. $wxPattern = '/^(10|11|12|13|14|15)\d{16}$/';
  567. //支付宝文档说明 https://opendocs.alipay.com/open/194/106039/
  568. $aliPattern = '/^(25|26|27|28|29|30)\d{14,22}$/';
  569. if (!preg_match($wxPattern, $authCode) && !preg_match($aliPattern, $authCode)) {
  570. $msg = '付款码错误,请使用微信或支付宝付款码';
  571. $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  572. //noticeUtil::push($remind . ' 编号009', '15280215347');
  573. util::success(['returnStatus' => 'FAILURE'], $msg);
  574. }
  575. } else {
  576. if (empty($authCode)) {
  577. util::fail('没有获取到支付码');
  578. }
  579. }
  580. $orderSn = $order->orderSn ?? '';
  581. $lsCodePayErrorKey = 'ls_code_pay_error_' . $id;
  582. $hasFailPay = Yii::$app->redis->executeCommand('GET', [$lsCodePayErrorKey]);
  583. //前面有付失败过,要重新生成单号
  584. if (!empty($hasFailPay)) {
  585. $oldOrderSn = $order->orderSn;
  586. $orderSn = orderSn::getOrderSn();
  587. $order->orderSn = $orderSn;
  588. $order->save();
  589. OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
  590. }
  591. $subject = '购买花材 ' . $orderSn;
  592. $totalFee = $order->mainPay ?? 0;
  593. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  594. try {
  595. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  596. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  597. $params = [
  598. 'appid' => 'OP00002119',
  599. 'serial_no' => '018b08cfddbd',
  600. 'merchant_no' => $shop->lklSjNo,
  601. 'term_no' => $shop->lklScanTermNo,
  602. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  603. 'lklCertificatePath' => $lklCertificatePath,
  604. ];
  605. $laResource = new Lakala($params);
  606. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  607. $scanParams = [
  608. 'orderSn' => $orderSn,
  609. 'amount' => $totalFee,
  610. 'capitalType' => $capitalType,
  611. 'notifyUrl' => $notifyUrl,
  612. 'subject' => $subject,
  613. 'authCode' => $authCode,
  614. ];
  615. // 复杂分支/关键逻辑:在调用外部支付接口前不开启事务,防止网络延迟卡死数据库连接
  616. $response = $laResource->scanPay($scanParams);
  617. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  618. // 复杂分支/关键逻辑:支付成功后,开启数据库事务,确保本地订单状态更新的原子性
  619. $connection = Yii::$app->db;
  620. $transaction = $connection->beginTransaction();
  621. try {
  622. $account_type = $response['resp_data']['account_type'] ?? '';
  623. $payWayType = dict::getDict('payWay', 'wxPay');
  624. if ($account_type == 'WECHAT') {
  625. $payWayType = dict::getDict('payWay', 'wxPay');
  626. }
  627. if ($account_type == 'ALIPAY') {
  628. $payWayType = dict::getDict('payWay', 'alipay');
  629. }
  630. $order->payWay = $payWayType;
  631. $transactionId = $response['resp_data']['trade_no'] ?? '';
  632. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  633. $order->save();
  634. $attach = '';
  635. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  636. $transaction->commit();
  637. } catch (\Exception $e) {
  638. $transaction->rollBack();
  639. throw $e;
  640. }
  641. //解决重复通知
  642. $cacheKey = 'hd_shop_order_pay_' . $orderSn;
  643. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  644. if (empty($has)) {
  645. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  646. $newOrder = OrderClass::getById($id, true);
  647. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  648. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  649. $newOrder->status = 4;
  650. $newOrder->save();
  651. }
  652. //打印小票
  653. OrderClass::onlinePrint($newOrder);
  654. HdDeliveryOrderClass::payAfter($newOrder);
  655. //语音播报
  656. ShopExtClass::hdGatheringReport($newOrder);
  657. $shopId = $newOrder->shopId ?? 0;
  658. $shop = ShopClass::getById($shopId, true);
  659. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  660. }
  661. util::success(['returnStatus' => 'SUCCESS']);
  662. } else {
  663. //标记有没付成功的次数,原因有可能是余额不足等
  664. Yii::$app->redis->executeCommand('SETEX', [$lsCodePayErrorKey, 1200, 'hasFail']);
  665. $msg = $response['msg'] ?? '';
  666. $retCode = $response['code'] ?? '';
  667. $fullMsg = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  668. if ($retCode == 'BBS10000' || $retCode == 'BBS11105') {
  669. $shopId = $order->shopId;
  670. ShopExtClass::remindInputPassword($shopId);
  671. }
  672. //noticeUtil::push($fullMsg . ' ' . $retCode . ' 编号008', '15280215347');
  673. util::success(['returnStatus' => 'FAILURE', 'returnCode' => $retCode], $msg);
  674. }
  675. } catch (\Exception $e) {
  676. Yii::error("零售端支付失败原因:" . $e->getMessage());
  677. util::fail('支付失败');
  678. }
  679. }
  680. //开单操作 ssh 20220316
  681. public function actionCreateOrder()
  682. {
  683. $post = Yii::$app->request->post();
  684. $post['sjId'] = $this->sjId;
  685. $post['shopId'] = $this->shopId;
  686. $post['mainId'] = $this->mainId ?? 0;
  687. $shop = $this->shop;
  688. if ($shop->memberLevelSet == 0) {
  689. //util::fail('请先设置会员等级');
  690. }
  691. $now = time();
  692. $orderValidTime = 600;
  693. $expireTime = $now + $orderValidTime;
  694. $post['deadline'] = $expireTime;
  695. $post['staffId'] = $this->shopAdminId ?? 0;
  696. $post['staffName'] = $this->shopAdmin->name ?? '';
  697. $post['flowerNum'] = isset($post['flowerNum']) && $post['flowerNum'] > 0 ? $post['flowerNum'] : 0;
  698. $version = $post['version'] ?? 0; //验证已移至 CreateOrderForm
  699. if ($version < 3) {
  700. util::fail('请升级版本,或用小程序');
  701. }
  702. //默认情况开单员工和收款员工是同个人
  703. $staffId = $this->shopAdminId ?? 0;
  704. $staffName = $this->shopAdmin->name ?? '';
  705. if (empty($post['shopAdminId'])) {
  706. $post['shopAdminId'] = $staffId;
  707. $post['shopAdminName'] = $staffName;
  708. }
  709. if (empty($post['getStaffId'])) {
  710. $post['getStaffId'] = $staffId;
  711. $post['getStaffName'] = $this->shopAdmin->name ?? '';
  712. }
  713. $groupId = !empty($post['groupId']) ? $post['groupId'] : 0;
  714. $post['fromType'] = $post['fromType'] ?? 1;
  715. if ($post['fromType'] == dict::getDict('fromType', 'friend')) {
  716. if (empty($post['bookName'])) {
  717. util::fail('请填写订花人姓名');
  718. }
  719. }
  720. $customId = $post['customId'] ?? 0;
  721. $custom = CustomClass::getById($customId, true);
  722. if (empty($custom)) {
  723. util::fail('没有找到客户哦');
  724. }
  725. $hdId = $custom->hdId ?? 0;
  726. $hd = HdClass::getById($hdId, true);
  727. if (empty($hd)) {
  728. util::fail('客户对应的花店信息缺失,编号869');
  729. }
  730. $hdName = $hd->name ?? '';
  731. $post['hdId'] = $hdId;
  732. $post['hdName'] = $hdName;
  733. $customName = $custom->name ?? '';
  734. $post['customName'] = $customName;
  735. $post['customNamePy'] = stringUtil::py($customName);
  736. if (!empty($post['receiveMobile'])) {
  737. if (!stringUtil::isMobile($post['receiveMobile'])) {
  738. util::fail('请填写正确的收花人手机号');
  739. }
  740. }
  741. if (!empty($post['bookMobile'])) {
  742. if (!stringUtil::isMobile($post['bookMobile'])) {
  743. util::fail('请填写正确的订花人手机号');
  744. }
  745. }
  746. $hasPay = $post['hasPay'] ?? dict::getDict('hasPay', 'unPay');
  747. $post['sendType'] = $post['sendType'] ?? 1;
  748. $forward = $post['forward'] ?? 0;
  749. if ($forward == 1) {
  750. if ($hasPay != 1) {
  751. util::fail('红冲订单只能走线下转账');
  752. }
  753. $historyDate = $post['historyDate'] ?? '';
  754. if (!empty($historyDate)) {
  755. if ($historyDate != date("Y-m-d")) {
  756. util::fail('红冲订单不能修改账单日期,只能今天');
  757. }
  758. }
  759. }
  760. $productJson = $post['product'] ?? '';
  761. $productList = [];
  762. if (!empty($productJson)) {
  763. $productList = json_decode($productJson, true);
  764. }
  765. if (empty($productList) && empty($groupId)) {
  766. //商家手机上开单并生成制作单
  767. if (!empty($post['unitGoodsPrice'])) {
  768. util::fail('此功能停用,有需要请联系管理员');
  769. $unitGoodsPrice = $post['unitGoodsPrice'];
  770. if (!is_numeric($unitGoodsPrice)) {
  771. util::fail('请输入正确的单价');
  772. }
  773. $productList = GoodsClass::orderCreateGoods($post);
  774. }
  775. }
  776. //直接收款
  777. $zjGathering = $post['zjGathering'] ?? 0;
  778. if ($zjGathering == 1) {
  779. $lsGoodsPrice = $post['lsGoodsPrice'] ?? 0;
  780. if (!is_numeric($lsGoodsPrice) || $lsGoodsPrice <= 0) {
  781. util::fail('请填写价格');
  782. }
  783. //直接收款不需要打印小票
  784. $post['needPrint'] = dict::getDict('needPrint', 'noNeed');
  785. $shopId = $this->shopId;
  786. $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  787. $zjGatheringItem = !empty($ext) ? $ext->zjGatheringItem : 0;
  788. if (empty($zjGatheringItem)) {
  789. util::fail('请设置直接收款的商品');
  790. }
  791. $zjGatheringItemInfo = ProductClass::getById($zjGatheringItem, true);
  792. if (empty($zjGatheringItemInfo)) {
  793. util::fail('请设置直接收款的商品哈');
  794. }
  795. $productList = [['productId' => $zjGatheringItem, 'unitType' => 0, 'num' => 1, 'property' => '1', 'unitPrice' => $lsGoodsPrice]];
  796. }
  797. $callErrand = $post['callErrand'] ?? 0;
  798. if ($callErrand == 1) {
  799. $shopId = $this->shopId;
  800. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  801. if (!empty($shopExt) && $shopExt->orderFlow == 0) {
  802. util::fail('下单后要变待发货,才能直接发跑腿');
  803. }
  804. }
  805. $connection = Yii::$app->db;
  806. $transaction = $connection->beginTransaction();
  807. try {
  808. $post['product'] = $productList;
  809. $reduceStock = $post['reduceStock'] ?? 0;
  810. if ($reduceStock == 1) {
  811. //如果扣除库,则走另外一条路
  812. $return = OrderClass::reduceMyStock($post, $this->shop, $custom);
  813. $transaction->commit();
  814. util::success($return);
  815. }
  816. //解决开单提交订单时,别人修改价格,造成提交价格不是真实卖价问题!!
  817. $dealPrice = $post['dealPrice'] ?? 0;
  818. //解决重复提交
  819. util::checkRepeatCommit($this->adminId . '_' . $dealPrice, 3);
  820. $totalNum = 0;
  821. if ($dealPrice == 0) {
  822. $productIds = [];
  823. $hsIds = [];
  824. foreach ($productList as $pv) {
  825. $property = $pv['property'] ?? 0;
  826. $puId = $pv['productId'] ?? 0;
  827. if ($property == 0) {
  828. $hsIds[] = $puId;
  829. } else {
  830. $productIds[] = $puId;
  831. }
  832. }
  833. $itemInfo = [];
  834. if (!empty($productIds)) {
  835. $itemInfo = ProductClass::getByIds($productIds, null, 'id');
  836. }
  837. $hsInfo = [];
  838. if (!empty($hsIds)) {
  839. $hsInfo = GoodsClass::getByIds($hsIds, null, 'id');
  840. }
  841. $diff = [];
  842. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  843. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  844. $level = 0;
  845. foreach ($productList as $currentProduct) {
  846. $property = $currentProduct['property'] ?? 0;
  847. $currentPrice = $currentProduct['unitPrice'] ?? 0;
  848. $currentId = $currentProduct['productId'] ?? 0;
  849. if ($property == 1) {
  850. $systemInfo = $itemInfo[$currentId] ?? [];
  851. if (!empty($systemInfo)) {
  852. $name = $systemInfo['name'] ?? '';
  853. $systemPrice = \bizGhs\product\classes\ProductClass::getFinalPrice($systemInfo, $level, $priceMap, $addPriceMap);
  854. if (floatval($currentPrice) != floatval($systemPrice)) {
  855. $diff[] = [
  856. 'name' => $name,
  857. 'price' => $systemPrice,
  858. 'kdPrice' => $currentPrice,
  859. ];
  860. }
  861. }
  862. } else {
  863. $systemInfo = $hsInfo[$currentId] ?? [];
  864. if (!empty($systemInfo)) {
  865. $params = [];
  866. $name = $systemInfo['name'] ?? '';
  867. $hsData = GoodsClass::getFinalPrice($systemInfo, $shop, $custom, $params);
  868. $systemPrice = $hsData['price'] ?? 0;
  869. if ($systemInfo['priceType'] == 1) {
  870. if (floatval($currentPrice) != floatval($systemPrice)) {
  871. $diff[] = [
  872. 'name' => $name,
  873. 'price' => $systemPrice,
  874. 'kdPrice' => $currentPrice,
  875. ];
  876. }
  877. }
  878. }
  879. }
  880. $num = $currentProduct['num'];
  881. $totalNum = bcadd($totalNum, $num);
  882. }
  883. if (!empty($diff)) {
  884. util::success(['diff' => $diff, 'respondType' => 'priceError']);
  885. }
  886. }
  887. //红包使用,多有处,关键词 use_hb_action
  888. $hbId = $post['hbId'] ?? 0;
  889. $hb = null;
  890. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  891. $hb = HbClass::getById($hbId, true);
  892. if (!empty($hb)) {
  893. if ($hb->customId != $customId) {
  894. util::fail('不是这个客户的红包');
  895. }
  896. if ($hb->amount != $post['hbAmount']) {
  897. util::fail('红包错误'); //红包数据可能被串改
  898. }
  899. if ($hb->status == 1) {
  900. util::fail('红包已使用');
  901. }
  902. if ($hb->status == -1) {
  903. util::fail('红包已作废');
  904. }
  905. if ($hb->endTime < time()) {
  906. $hb->status = -1;
  907. $hb->save();
  908. util::fail('红包已失效');
  909. }
  910. if ($hb->beginTime > time()) {
  911. util::fail('红包可使用期未到');
  912. }
  913. // 按适用范围校验最低消费
  914. HbScopeClass::assertMinConsume($hb, $post['product'] ?? [], $post['modifyPrice'] ?? 0);
  915. if ($this->shop->rechargeWeal == 3) {
  916. // 判断支付方式是否是余额支付
  917. if ($hasPay != dict::getDict('hasPay', 'balance')) {
  918. util::fail('用红包要用余额支付');
  919. } else {
  920. if ($custom->balance < $post['modifyPrice']) {
  921. util::fail('用红包要用余额支付(您的余额不足)');
  922. }
  923. }
  924. }
  925. } else {
  926. Yii::error('没有找到红包,hbId: ', $hbId . ' ' . __METHOD__);
  927. util::fail('红包无效');
  928. }
  929. }
  930. $post['bigNum'] = $totalNum;
  931. //多处调用这个方法,注意同步修改,搜索关键词 createHdNewOrder
  932. $return = OrderService::createHdOrder($post, $custom, $hasPay);
  933. if (!empty($hb)) {
  934. $hb->status = 1;
  935. $hb->orderId = $return->id;
  936. $hb->save();
  937. }
  938. $staff = $this->shopAdmin;
  939. //售后开付款单,库存要变化,关系要建立,多处需要同步修改 sh_pay_change ssh
  940. OrderClass::shPayChange($return, $shop, $staff);
  941. //打印小票和语音播报等使用
  942. $id = $return->id ?? 0;
  943. $order = OrderClass::getById($id, true);
  944. //如果需要生成制作单
  945. $needWork = $post['needWork'] ?? 0;
  946. if ($needWork == 1) {
  947. $main = $this->main;
  948. WorkClass::needWork($order, $main);
  949. $has = WorkClass::getByCondition(['orderId' => $id], true);
  950. if (!empty($has)) {
  951. $return->hasWork = 1;
  952. $return->save();
  953. }
  954. }
  955. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  956. if ($order->getGoods == 1 && $order->sendType == 1 && $order->status == 2) {
  957. $order->status = 4;
  958. $order->save();
  959. DistributionCommissionClass::onRetailOrderCompleted((int)$order->id);
  960. }
  961. $transaction->commit();
  962. if ($order->fromType == 3 || $order->fromType == 4) {
  963. //除了客服号下单和美团下单,其它情况允许打小票
  964. } else {
  965. //前台打小票
  966. OrderClass::onlinePrint($order);
  967. }
  968. //订单发跑腿流程
  969. HdDeliveryOrderClass::prepareAskData($post, $order);
  970. //前台提示收款多少钱
  971. ShopExtClass::hdGatheringReport($order);
  972. //前台提醒出示付款码
  973. if (isset($order->status) && $order->status == 1) {
  974. if (isset($post['isCashier']) && $post['isCashier'] == 1) {
  975. ShopExtClass::pleasePayReport($order);
  976. }
  977. }
  978. $shopId = $order->shopId ?? 0;
  979. $shop = ShopClass::getById($shopId, true);
  980. WxMessageClass::gatheringIncomeInform($shop, $order);
  981. if ($needWork == 1) {
  982. //新制作单提示
  983. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  984. ShopExtClass::newWorkRemind($shopExt, $order);
  985. }
  986. util::success($return);
  987. } catch (\Exception $e) {
  988. $transaction->rollBack();
  989. Yii::error("下单失败原因:" . $e->getMessage());
  990. util::fail('下单失败');
  991. }
  992. }
  993. //下单要用到的相关信息 ssh 2019.12.6
  994. public function actionOrderRelate()
  995. {
  996. $regionTree = RegionService::tree();
  997. $shop = $this->shop->attributes;
  998. $freight = MerchantExtendService::getFreight($this->sjExtend);
  999. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  1000. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  1001. util::success($out);
  1002. }
  1003. //余额支付 ssh 2019.12.6
  1004. public function actionBalancePay()
  1005. {
  1006. $post = Yii::$app->request->post();
  1007. $orderSn = $post['orderSn'] ?? 0;
  1008. $payPassword = $post['payPassword'] ?? 0;
  1009. $couponId = $post['couponId'] ?? 0;
  1010. $order = OrderService::getByOrderSn($orderSn);
  1011. $userId = $this->adminId;
  1012. $user = UserService::getUserInfo($userId);
  1013. //验证支付密码是否正确
  1014. UserService::validPayPassword($payPassword, $user);
  1015. //支付前验证订单有效性
  1016. OrderService::checkBeforePay($order);
  1017. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1018. $totalFee = $order['prePrice'];
  1019. $sourceType = 0;
  1020. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  1021. $actPrice = $discountData['price'];
  1022. $callbackParams = [];
  1023. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  1024. $balance = $respond['balance'] ?? 0;
  1025. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  1026. }
  1027. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  1028. public function actionWxPay()
  1029. {
  1030. ini_set('date.timezone', 'Asia/Shanghai');
  1031. $post = Yii::$app->request->post();
  1032. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1033. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1034. $order = OrderService::getByOrderSn($orderSn);
  1035. $orderId = $order['id'];
  1036. //验证优惠券是否还有效
  1037. if (!empty($couponId)) {
  1038. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  1039. }
  1040. //支付前验证订单有效性
  1041. OrderService::checkBeforePay($order);
  1042. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  1043. $totalFee = $order['realPrice'];
  1044. //小程序使用miniOpenId
  1045. if (httpUtil::isMiniProgram()) {
  1046. $openId = $this->user['miniOpenId'];
  1047. } else {
  1048. $openId = $this->user['openId'];
  1049. }
  1050. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1051. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  1052. $wxPayType = 0;
  1053. if (httpUtil::isMiniProgram()) {
  1054. $wxPayType = 1;
  1055. }
  1056. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  1057. //订单30分钟后过期
  1058. $now = time();
  1059. $expireTime = $now + 1800;
  1060. $wx = Yii::getAlias("@vendor/weixin");
  1061. require_once($wx . '/lib/WxPay.Api.php');
  1062. require_once($wx . '/example/WxPay.JsApiPay.php');
  1063. $input = new \WxPayUnifiedOrder();
  1064. $input->SetBody($name);
  1065. $input->SetOut_trade_no($orderSn);
  1066. $input->SetTotal_fee($totalFee * 100);
  1067. $input->SetTime_start(date("YmdHis", $now));
  1068. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  1069. $input->SetTime_expire(date("YmdHis", $expireTime));
  1070. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1071. $input->SetTrade_type("JSAPI");
  1072. //花卉宝代为申请的微信支付
  1073. $merchantExtend = $this->sjExtend->attributes;
  1074. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1075. $input->SetSub_openid($openId);
  1076. } else {
  1077. $input->SetOpenid($openId);
  1078. }
  1079. //小程序使用miniAppId
  1080. if (httpUtil::isMiniProgram()) {
  1081. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1082. }
  1083. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1084. $tools = new \JsApiPay();
  1085. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1086. $newParams = json_decode($jsApiParameters, true);
  1087. //已请求微信不能修改价格
  1088. $updateData = [];
  1089. $updateData['modPrice'] = 0;
  1090. if (empty($order['deadline'])) {
  1091. $updateData['deadline'] = $expireTime;
  1092. }
  1093. OrderService::updateById($orderId, $updateData);
  1094. util::success($newParams);
  1095. }
  1096. //快捷付款订单
  1097. public function actionFastPay()
  1098. {
  1099. ini_set('date.timezone', 'Asia/Shanghai');
  1100. $post = Yii::$app->request->post();
  1101. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  1102. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->sj);
  1103. //验证门店是否有效
  1104. $shopInfo = ShopService::getById($shopId);
  1105. ShopService::valid($shopInfo, $this->sjId);
  1106. $post['shopId'] = $shopId;
  1107. //默认门店订单
  1108. $store = isset($post['store']) ? $post['store'] : 1;
  1109. $post['store'] = $store;
  1110. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  1111. $sourceType = $this->isWx ? 0 : 1;
  1112. if (httpUtil::isMiniProgram()) {
  1113. $sourceType = 2;
  1114. }
  1115. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  1116. //兼容旧系统sourceType=3表示朋友圈来源
  1117. $fromType = $sourceType == 3 ? 2 : 0;
  1118. $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
  1119. $post['userId'] = $this->adminId;
  1120. $custom = $this->custom;
  1121. $post['bookName'] = $custom['userName'] ?? '';
  1122. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  1123. $bookMobile = empty($bookMobile) && isset($custom['mobile']) && !empty($custom['mobile']) ? $custom['mobile'] : $bookMobile;
  1124. $post['bookMobile'] = $bookMobile;
  1125. $prePrice = round($post['prePrice'], 2);
  1126. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1127. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  1128. $actPrice = $discountData['price'];
  1129. $post['discountType'] = $discountData['discountType'];
  1130. $post['discountAmount'] = $discountData['discountAmount'];
  1131. $post['actPrice'] = $actPrice;
  1132. $post['realPrice'] = $actPrice;
  1133. $post['payStyle'] = 0;
  1134. $post['sjId'] = $this->sjId;
  1135. $now = time();
  1136. $expireTime = $now + 300;//订单5分钟后过期
  1137. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1138. $post['deadline'] = $expireTime;
  1139. if ($actPrice <= 0) {
  1140. util::fail('请填写正确的金额');
  1141. }
  1142. //微信支付订单提交不能修改价格
  1143. $post['modPrice'] = $this->isWx ? 0 : 1;
  1144. $post['sourceType'] = $sourceType;
  1145. $post['goodsNum'] = 1;
  1146. $post['fromType'] = $fromType;
  1147. $order = OrderService::addOrder($post);
  1148. $orderId = $order['id'];
  1149. $orderSn = $order['orderSn'];
  1150. $sjId = $this->sjId;
  1151. if ($payWay == 0) {
  1152. $orderId = $order['id'];
  1153. $name = '购买商品';
  1154. $totalFee = $actPrice;
  1155. $user = UserService::getById($this->adminId);
  1156. $openId = isset($user['openId']) ? $user['openId'] : 0;
  1157. if (httpUtil::isMiniProgram()) {
  1158. //小程序使用miniOpenId
  1159. $openId = $user['miniOpenId'];
  1160. }
  1161. if (empty($openId)) {
  1162. util::fail('没有找到客户的openId');
  1163. }
  1164. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1165. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  1166. $wxPayType = 0;
  1167. if (httpUtil::isMiniProgram()) {
  1168. $wxPayType = 1;
  1169. }
  1170. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  1171. $wx = Yii::getAlias("@vendor/weixin");
  1172. require_once($wx . '/lib/WxPay.Api.php');
  1173. require_once($wx . '/example/WxPay.JsApiPay.php');
  1174. $input = new \WxPayUnifiedOrder();
  1175. $input->SetBody($name);
  1176. $input->SetOut_trade_no($orderSn);
  1177. $input->SetTotal_fee($totalFee * 100);
  1178. $input->SetTime_start(date("YmdHis", $now));
  1179. $input->SetAttach($attach);
  1180. //设置订单有效期5分钟
  1181. $input->SetTime_expire(date("YmdHis", $expireTime));
  1182. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1183. $input->SetTrade_type("JSAPI");
  1184. //花卉宝代为申请的微信支付
  1185. $merchantExtend = $this->sjExtend->attributes;
  1186. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1187. $input->SetSub_openid($openId);
  1188. } else {
  1189. $input->SetOpenid($openId);
  1190. }
  1191. //小程序使用miniAppId
  1192. if (httpUtil::isMiniProgram()) {
  1193. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1194. }
  1195. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  1196. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1197. $tools = new \JsApiPay();
  1198. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1199. $newParams = json_decode($jsApiParameters, true);
  1200. $newParams['orderId'] = $orderId;
  1201. util::success($newParams);
  1202. } elseif ($payWay == 1) {
  1203. $extend = MerchantExtendService::getBySjId($sjId);
  1204. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  1205. util::fail('支付宝付款即将开通...');
  1206. }
  1207. $config = [
  1208. //应用ID,您的APPID。
  1209. 'app_id' => $extend['alipayPId'],
  1210. //商户私钥,您的原始格式RSA私钥
  1211. 'merchant_private_key' => $extend['alipayKey'],
  1212. //异步通知地址
  1213. 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
  1214. //同步跳转
  1215. 'return_url' => "",
  1216. //编码格式
  1217. 'charset' => "UTF-8",
  1218. //签名方式
  1219. 'sign_type' => "RSA2",
  1220. //支付宝网关
  1221. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  1222. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  1223. 'alipay_public_key' => $extend['alipayPublicKey'],
  1224. ];
  1225. Yii::info(json_encode($config) . ' aplipay config');
  1226. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  1227. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  1228. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  1229. $totalFee = $order['realPrice'];
  1230. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  1231. $subject = '购买商品';//订单名称,必填
  1232. $total_amount = $totalFee;//付款金额,必填
  1233. $body = '';//商品描述,可空
  1234. $timeout_express = "1m";//超时时间
  1235. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1236. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  1237. $passBackParams = urlencode($passBackParams);
  1238. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  1239. $payRequestBuilder->setBody($body);
  1240. $payRequestBuilder->setSubject($subject);
  1241. $payRequestBuilder->setOutTradeNo($out_trade_no);
  1242. $payRequestBuilder->setTotalAmount($total_amount);
  1243. $payRequestBuilder->setTimeExpress($timeout_express);
  1244. //在异步通知时将该参数原样返回
  1245. $payRequestBuilder->setPassbackParams($passBackParams);
  1246. //同步通知
  1247. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  1248. //异步通知
  1249. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  1250. $payResponse = new \AlipayTradeService($config);
  1251. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  1252. //直接将支付宝的html返回给前端
  1253. echo $result;
  1254. } elseif ($payWay == 2) {
  1255. //余额支付
  1256. util::fail('暂不支持');
  1257. } else {
  1258. util::fail('无效的支付方式');
  1259. }
  1260. }
  1261. //订单评价
  1262. public function actionComment()
  1263. {
  1264. $post = Yii::$app->request->post();
  1265. $id = $post['id'];
  1266. $order = OrderService::getById($id);
  1267. OrderService::valid($order, $this->mainId);
  1268. if ($order['grade'] > 0) {
  1269. util::fail('您已经评过了');
  1270. }
  1271. OrderService::comment($post);
  1272. util::complete('提交成功');
  1273. }
  1274. //订单详情,不需要登陆可以查看,要有盐,给跑腿上查看订单信息用的
  1275. public function actionInfo()
  1276. {
  1277. $get = Yii::$app->request->get();
  1278. $id = $get['id'] ?? 0;
  1279. $salt = $get['salt'] ?? '';
  1280. $detail = OrderClass::getFullInfo($id);
  1281. if (empty($detail)) {
  1282. util::fail('没有找到订单');
  1283. }
  1284. if (empty($detail['salt'])) {
  1285. util::fail('没有找到订单信息');
  1286. }
  1287. if (empty($salt)) {
  1288. util::fail('请求参数错误呢');
  1289. }
  1290. if ($detail['salt'] != $salt) {
  1291. util::fail('不是你的订单');
  1292. }
  1293. util::success($detail);
  1294. }
  1295. //订单详情
  1296. public function actionDetail()
  1297. {
  1298. $id = Yii::$app->request->get('id', 0);
  1299. $detail = OrderClass::getFullInfo($id);
  1300. OrderService::valid($detail, $this->mainId);
  1301. $forwardMap = [];
  1302. if ($detail['forward'] == 1) {
  1303. //当前单如果已经是红冲订单,则取出其对应的原单
  1304. $map = OrderForwardClass::getByCondition(['shOrderId' => $id], true);
  1305. if (!empty($map)) {
  1306. $originOrderId = $map->orderId ?? 0;
  1307. $forwardMap['orderId'] = $originOrderId;
  1308. }
  1309. }
  1310. $detail['forwardMap'] = $forwardMap;
  1311. $shOrderMap = [];
  1312. if ($detail['hasForward'] == 1) {
  1313. $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
  1314. }
  1315. $detail['shOrderMap'] = $shOrderMap;
  1316. $main = $this->main;
  1317. //是否走红冲订单模式判断 ssh
  1318. $ret = OrderClass::ifShPay($detail, $main, 0);
  1319. $shAddPay = $ret['shAddPay'];
  1320. $shAddPayReason = $ret['shAddPayReason'];
  1321. $detail['shAddPay'] = $shAddPay;
  1322. $detail['shAddPayReason'] = $shAddPayReason;
  1323. util::success($detail);
  1324. }
  1325. /**
  1326. * 订单列表(PC/小程序共用)
  1327. * 支持图1独立筛选项:订单编号、货号、订单类型、配送方式、付款类型、人员关键词、创建时间
  1328. */
  1329. public function actionList()
  1330. {
  1331. $get = Yii::$app->request->get();
  1332. $searchText = $get['searchText'] ?? '';
  1333. $shopId = $this->shopId ?? 0;
  1334. if (empty($shopId)) {
  1335. //没有登录不显示数据
  1336. util::success(['list' => [], 'moreData' => 0, 'shop' => [], 'totalNum' => 0, 'totalPage' => 0]);
  1337. }
  1338. $where = [];
  1339. $where['shopId'] = $shopId;
  1340. if (!empty($get['customId'])) {
  1341. $where['customId'] = $get['customId'];
  1342. }
  1343. if (!empty($get['ids'])) {
  1344. $stringIds = $get['ids'];
  1345. $newIds = explode(',', $stringIds);
  1346. $where['id'] = ['in', $newIds];
  1347. }
  1348. $status = $get['status'] ?? 0;
  1349. if (!empty($status)) {
  1350. $where['status'] = $get['status'];
  1351. }
  1352. $debt = $get['debt'] ?? -1;
  1353. if ($debt > -1) {
  1354. $where['debt'] = $debt;
  1355. }
  1356. if (!empty($get['shopAdminId'])) {
  1357. $where['shopAdminId'] = $get['shopAdminId'];
  1358. }
  1359. // PC 端独立筛选:订单编号 / 货号
  1360. if (!empty($get['orderSn'])) {
  1361. $where['orderSn'] = ['like', trim((string)$get['orderSn'])];
  1362. }
  1363. if (!empty($get['sendNum'])) {
  1364. $where['sendNum'] = trim((string)$get['sendNum']);
  1365. }
  1366. // 订单类型 fromType:门店/商城/微信/美团/饿了么
  1367. if (isset($get['fromType']) && $get['fromType'] !== '' && (int)$get['fromType'] > -1) {
  1368. $where['fromType'] = (int)$get['fromType'];
  1369. }
  1370. // 配送方式 sendType
  1371. if (isset($get['sendType']) && $get['sendType'] !== '' && (int)$get['sendType'] > -1) {
  1372. $where['sendType'] = (int)$get['sendType'];
  1373. }
  1374. // 付款类型:兼容 payWay 或 onlinePay
  1375. if (isset($get['payWay']) && $get['payWay'] !== '' && (int)$get['payWay'] > -1) {
  1376. $where['payWay'] = (int)$get['payWay'];
  1377. }
  1378. if (isset($get['onlinePay']) && $get['onlinePay'] !== '' && (int)$get['onlinePay'] > -1) {
  1379. $where['onlinePay'] = (int)$get['onlinePay'];
  1380. }
  1381. // 下单人/收货人/姓名/手机号:多字段 OR 模糊匹配,先查 id 再并入 where(Base 条件不支持 OR)
  1382. if (!empty($get['keyword'])) {
  1383. $keywordIds = $this->findOrderIdsByKeyword($shopId, trim((string)$get['keyword']));
  1384. $where['id'] = ['in', !empty($keywordIds) ? $keywordIds : [0]];
  1385. }
  1386. // 按搜索词自动识别:纯数字查货号,否则查姓名(小程序兼容)
  1387. if (!empty($searchText)) {
  1388. $this->appendOrderListSearchWhere($where, $searchText);
  1389. }
  1390. if (isset($get['repeat']) && $get['repeat'] > -1) {
  1391. $where['repeat'] = $get['repeat'];
  1392. }
  1393. if (!empty($get['searchTime'])) {
  1394. $startTime = $get['startTime'] ?? '';
  1395. $endTime = $get['endTime'] ?? '';
  1396. $period = dateUtil::formatTime($get['searchTime'], $startTime, $endTime);
  1397. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1398. }
  1399. $list = OrderService::getOrderList($where);
  1400. $list['shop'] = $this->shop->attributes ?? [];
  1401. util::success($list);
  1402. }
  1403. //订单归类 ssh 2019.12.17
  1404. public function actionClassify()
  1405. {
  1406. $post = Yii::$app->request->post();
  1407. $id = $post['id'] ?? 0;
  1408. $order = OrderService::getById($id);
  1409. OrderService::valid($order, $this->mainId);
  1410. $categoryId = $post['categoryId'];
  1411. $usageId = $post['usageId'];
  1412. OrderService::classify($id, $categoryId, $usageId);
  1413. util::complete();
  1414. }
  1415. //更新配送单 ssh 2019.12.17
  1416. public function actionUpdateSheet()
  1417. {
  1418. $post = Yii::$app->request->post();
  1419. $id = $post['id'] ?? 0;
  1420. unset($post['id']);
  1421. $order = OrderService::getById($id);
  1422. OrderService::valid($order, $this->mainId);
  1423. OrderService::updateSheet($order, $post);
  1424. util::complete('提交成功');
  1425. }
  1426. //商家收款与发货 ssh 2019.12.18
  1427. public function actionGathering()
  1428. {
  1429. $post = Yii::$app->request->post();
  1430. $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
  1431. $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
  1432. $userId = $post['userId'] ?? 0;
  1433. $userInfo = UserService::getById($userId);
  1434. if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
  1435. util::fail('您选择的客户无效');
  1436. }
  1437. if ($price <= 0) {
  1438. util::fail('请输入金额');
  1439. }
  1440. $post['prePrice'] = $price;
  1441. $post['actPrice'] = $price;
  1442. $post['payWay'] = $payWay;
  1443. $post['sourceType'] = 1;
  1444. $post['userId'] = $userId;
  1445. $post['goodsNum'] = 1;
  1446. $post['orderName'] = '商品';
  1447. $shopId = MerchantService::getDefaultShopId($this->sj);
  1448. $post['shopId'] = $shopId;
  1449. $order = OrderService::addOrder($post);
  1450. $id = $order['id'];
  1451. $orderSn = $order['orderSn'];
  1452. //流水类型列表
  1453. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1454. $callbackParams = [];
  1455. switch ($payWay) {
  1456. case 0:
  1457. xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
  1458. break;
  1459. case 1:
  1460. xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
  1461. break;
  1462. case 2:
  1463. xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
  1464. break;
  1465. default:
  1466. util::fail('无效支付方式');
  1467. }
  1468. util::success($order);
  1469. }
  1470. //免发货管理 ssh 2020.1.6
  1471. public function actionWithoutSend()
  1472. {
  1473. $id = Yii::$app->request->get('id');
  1474. $order = OrderService::getById($id);
  1475. OrderService::valid($order, $this->mainId);
  1476. //配送流程变更
  1477. $currentFlow = OrderSendClass::withoutSend($order);
  1478. util::success(['currentFlow' => $currentFlow]);
  1479. }
  1480. //修改价格 ssh 2020.1.6
  1481. public function actionUpdatePrice()
  1482. {
  1483. $id = Yii::$app->request->get('id');
  1484. $price = Yii::$app->request->get('price', 1);
  1485. $order = OrderService::getById($id);
  1486. OrderService::valid($order, $this->mainId);
  1487. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1488. util::fail('已发起支付,不能修改价格');
  1489. }
  1490. OrderService::updateById($id, ['actPrice' => $price]);
  1491. util::complete('修改成功');
  1492. }
  1493. //配送单 ssh 2020.2.29
  1494. public function actionGetDeliverDetail()
  1495. {
  1496. $id = Yii::$app->request->get('id', 0);
  1497. $order = OrderService::getById($id);
  1498. OrderService::valid($order, $this->mainId);
  1499. $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
  1500. $reachPeriodId = $order['reachPeriod'];
  1501. $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
  1502. $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
  1503. $bookName = isset($order['bookName']) ? $order['bookName'] : '';
  1504. $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
  1505. if (isset($order['anonymity']) && $order['anonymity'] == 1) {
  1506. $bookName = '--';
  1507. $bookMobile = '--';
  1508. }
  1509. $data = [
  1510. 'reachDate' => $reachDate . ' ' . $reachPeriod,
  1511. 'orderSn' => $order['orderSn'],
  1512. 'receiveUserName' => $order['receiveUserName'],
  1513. 'receiveMobile' => $order['receiveMobile'],
  1514. 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
  1515. 'cardInfo' => $order['cardInfo'],
  1516. 'bookMobile' => $bookMobile,
  1517. 'bookName' => $bookName,
  1518. 'remark' => $order['remark'],
  1519. 'sendNum' => $order['sendNum'],
  1520. 'telephone' => 18030142050,
  1521. 'printTime' => '',
  1522. 'img' => '',
  1523. ];
  1524. util::success($data);
  1525. }
  1526. //运费计算 lqh 2021.4.12 暂反回固定
  1527. public function actionFreight()
  1528. {
  1529. util::success(['sedCost' => 10]);
  1530. }
  1531. /**
  1532. * 订单列表搜索条件:纯数字按货号精确匹配,否则按客户姓名模糊匹配
  1533. * @param array $where 查询条件(引用传递)
  1534. * @param string $searchText 搜索关键词
  1535. */
  1536. private function appendOrderListSearchWhere(&$where, $searchText)
  1537. {
  1538. $searchText = trim((string)$searchText);
  1539. if ($searchText === '') {
  1540. return;
  1541. }
  1542. if (preg_match('/^\d+$/', $searchText)) {
  1543. $where['sendNum'] = $searchText;
  1544. return;
  1545. }
  1546. $where['customName'] = ['like', $searchText];
  1547. }
  1548. /**
  1549. * 按人员/手机关键词查订单 id(下单人、收货人、客户名、开单人、手机号)
  1550. * @param int $shopId 门店 id
  1551. * @param string $keyword 关键词
  1552. * @return array
  1553. */
  1554. private function findOrderIdsByKeyword($shopId, $keyword)
  1555. {
  1556. if ($keyword === '' || empty($shopId)) {
  1557. return [];
  1558. }
  1559. return (new \yii\db\Query())
  1560. ->select('id')
  1561. ->from(\bizHd\order\models\Order::tableName())
  1562. ->where(['shopId' => $shopId])
  1563. ->andWhere([
  1564. 'or',
  1565. ['like', 'bookName', $keyword],
  1566. ['like', 'receiveUserName', $keyword],
  1567. ['like', 'customName', $keyword],
  1568. ['like', 'shopAdminName', $keyword],
  1569. ['like', 'bookMobile', $keyword],
  1570. ['like', 'receiveMobile', $keyword],
  1571. ])
  1572. ->column();
  1573. }
  1574. }