OrderController.php 75 KB

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