PurchaseController.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. <?php
  2. namespace hd\controllers;
  3. use biz\admin\classes\AdminClass;
  4. use biz\common\classes\GhsNotifyClass;
  5. use biz\ghs\classes\GhsClass;
  6. use biz\shop\classes\ShopClass;
  7. use biz\shop\classes\ShopExtClass;
  8. use bizGhs\custom\classes\AccountMoneyClass;
  9. use bizGhs\custom\classes\CustomClass;
  10. use bizGhs\express\classes\GhsDeliveryOrderClass;
  11. use bizGhs\order\classes\OrderClass;
  12. use bizGhs\order\classes\OrderForwardClass;
  13. use bizGhs\order\classes\ShMethodClass;
  14. use bizHd\cg\classes\CgMergeSnClass;
  15. use bizHd\purchase\classes\PurchaseClass;
  16. use bizHd\purchase\classes\PurchaseItemClass;
  17. use bizHd\purchase\services\PurchaseService;
  18. use bizGhs\product\classes\ProductClass;
  19. use bizHd\wx\classes\WxOpenClass;
  20. use common\components\dateUtil;
  21. use common\components\delivery\util\DeliveryQuoteUtil;
  22. use common\components\dict;
  23. use common\components\imgUtil;
  24. use common\components\mapUtil;
  25. use common\components\noticeUtil;
  26. use common\components\orderSn;
  27. use Yii;
  28. use common\components\util;
  29. use bizGhs\order\services\OrderService;
  30. use common\components\lakala\Lakala;
  31. use common\components\qrCodeUtil;
  32. use common\components\push;
  33. class PurchaseController extends BaseController
  34. {
  35. public $guestAccess = ['detail', 'ali-pay', 'get-ali-pay-code', 'wx-pay', 'merge-order-list', 'debt-list'];
  36. //取消采购单 ssh 20250710
  37. public function actionCancel()
  38. {
  39. $get = Yii::$app->request->get();
  40. $id = $get['id'] ?? '';
  41. $info = PurchaseClass::getById($id, true);
  42. if (empty($info)) {
  43. util::fail('没有找到采购单');
  44. }
  45. if (!isset($info->mainId) || $info->mainId != $this->mainId) {
  46. util::fail('访问错误');
  47. }
  48. if ($info->status == 5) {
  49. util::fail('已取消');
  50. }
  51. if ($info->status != 1) {
  52. util::fail('不能取消');
  53. }
  54. PurchaseService::expire($info);
  55. util::complete('已取消');
  56. }
  57. //获取支付宝付款码 ssh 20240713
  58. public function actionGetAliPayCode()
  59. {
  60. $get = Yii::$app->request->get();
  61. $orderSn = $get['orderSn'] ?? '';
  62. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  63. if (empty($info)) {
  64. util::fail('没有找到采购单');
  65. }
  66. if (!isset($info->mainId) || $info->mainId != $this->mainId) {
  67. //重要,这个不能限制,因为开单分享给客户付款的,要显示支付宝二维码,限制了会不显示!!!!!! shish 20260326
  68. //util::fail('无法访问!');
  69. }
  70. if (getenv('YII_ENV') == 'production') {
  71. $url = "https://mall.huahb.cn/#/admin/cg/alipay?orderSn={$orderSn}";
  72. } else {
  73. $url = "https://mall.huaml.com/#/admin/cg/alipay?orderSn={$orderSn}";
  74. }
  75. $unique = "order_ali_pay_" . $orderSn;
  76. $imgUrl = qrCodeUtil::generateRechargeQrCode($url, $unique);
  77. $imageUrl = imgUtil::groupImg($imgUrl);
  78. util::success(['imgUrl' => $imageUrl]);
  79. }
  80. //确认收货 ssh 20231119
  81. public function actionConfirmTake()
  82. {
  83. $get = Yii::$app->request->get();
  84. $id = $get['id'] ?? 0;
  85. $info = PurchaseClass::getById($id, true);
  86. if (empty($info)) {
  87. util::fail('没有找到采购单');
  88. }
  89. if (isset($info->mainId) == false || $info->mainId != $this->mainId) {
  90. util::fail('无法访问!!');
  91. }
  92. PurchaseClass::confirmTake($info);
  93. util::complete('确认成功');
  94. }
  95. //这个接口只能用于
  96. public function actionGetFullInfo()
  97. {
  98. $get = Yii::$app->request->get();
  99. $id = $get['id'] ?? 0;
  100. $info = PurchaseClass::getById($id);
  101. if (empty($info)) {
  102. util::fail('没有找到采购单');
  103. }
  104. if (!isset($info['mainId']) || $info['mainId'] != $this->mainId) {
  105. util::fail('无法访问。。。');
  106. }
  107. $orderSn = $info['orderSn'] ?? '';
  108. $ghsShopId = $info['ghsShopId'] ?? 0;
  109. if (empty($ghsShopId)) {
  110. $ghsId = $info['ghsId'] ?? 0;
  111. if (!empty($ghsId)) {
  112. $ghs = GhsClass::getById($ghsId, true);
  113. $ghsShopId = $ghs->shopId ?? 0;
  114. PurchaseClass::updateById($id, ['ghsShopId' => $ghsShopId]);
  115. }
  116. }
  117. //申请售后 0禁止 1允许
  118. $afterSale = 1;
  119. //下单后多少小时内可以售后,0不限制
  120. $saleHour = 12;
  121. //是否可以仅退款 1支持 0不支持
  122. $refundOnlyPrice = 1;
  123. //售后是否要求上传照片 0不要求 1必须
  124. $refundMustImg = 0;
  125. if (!empty($ghsShopId)) {
  126. $shop = ShopClass::getByCondition(['id' => $ghsShopId], false, false, 'id,afterSale,saleHour,refundOnlyPrice,refundMustImg');
  127. $afterSale = $shop['afterSale'] ?? 1;
  128. $saleHour = $shop['saleHour'] ?? 12;
  129. $refundOnlyPrice = $shop['refundOnlyPrice'] ?? 1;
  130. $refundMustImg = $shop['refundMustImg'] ?? 0;
  131. }
  132. //售后规则
  133. $info['afterSaleRule'] = ['afterSale' => $afterSale, 'saleHour' => $saleHour, 'refundOnlyPrice' => $refundOnlyPrice, 'refundMustImg' => $refundMustImg];
  134. $list = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
  135. if (!empty($list)) {
  136. foreach ($list as $key => $item) {
  137. $shortCover = $item['cover'] ?? '';
  138. $cover = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
  139. $bigCover = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_700,w_700";
  140. $list[$key]['cover'] = $cover;
  141. $list[$key]['bigCover'] = $bigCover;
  142. $list[$key]['shortCover'] = $shortCover;
  143. }
  144. }
  145. $info['product'] = $list;
  146. util::success($info);
  147. }
  148. //虚拟供货商的采购 ssh 20230308
  149. public function actionAddVirtualCg()
  150. {
  151. $post = Yii::$app->request->post();
  152. $ghsId = $post['ghsId'] ?? 0;
  153. $payMode = $post['payMode'] ?? 0;
  154. $payWay = $post['payWay'] ?? 0;
  155. $ghsInfo = GhsClass::getById($ghsId);
  156. if (empty($ghsInfo)) {
  157. util::fail('没有找到供货商');
  158. }
  159. if (isset($ghsInfo['mainId']) && !empty($ghsInfo['mainId']) && $ghsInfo['mainId'] == $ghsInfo['ownMainId']) {
  160. util::fail('不能向自己的店买花');
  161. }
  162. $connection = Yii::$app->db;
  163. $transaction = $connection->beginTransaction();
  164. $transactionFinished = false;
  165. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  166. if ($transactionFinished) {
  167. return;
  168. }
  169. ProductClass::rollbackLimitBuySnapshot();
  170. if ($transaction->isActive) {
  171. $transaction->rollBack();
  172. }
  173. });
  174. try {
  175. $post['book'] = $post['book'] ?? 0;
  176. $post['sjId'] = $this->sjId;
  177. $post['shopId'] = $this->shopId;
  178. $post['shopAdminId'] = $this->shopAdminId;
  179. $post['ghsId'] = $ghsId;
  180. $post['ghsName'] = $ghsInfo['name'] ?? '';
  181. $post['ghsMobile'] = $ghsInfo['mobile'] ?? '';
  182. $post['ghsAvatar'] = $ghsInfo['avatar'] ?? '';
  183. $post['ghsFullAddress'] = $ghsInfo['fullAddress'] ?? '';
  184. $customId = $ghsInfo['customId'] ?? 0;
  185. $post['customId'] = $customId;
  186. $shopAdmin = $this->shopAdmin ?? null;
  187. $name = $shopAdmin->name ?? '';
  188. $post['shopAdminName'] = $name;
  189. $post['mainId'] = $this->mainId;
  190. $product = $post['product'] ?? '';
  191. $productList = json_decode($product, true);
  192. //判断product数据是不是同个供货商的
  193. $ids = array_unique(array_filter(array_column($productList, 'productId')));
  194. $productInfoList = ProductClass::getByIds($ids, null, 'id');
  195. if (!empty($productInfoList)) {
  196. foreach ($productInfoList as $currentInfo) {
  197. if (isset($currentInfo['mainId']) == false || $currentInfo['mainId'] != $this->mainId) {
  198. util::fail('只能选一家的商品,请清空重选。');
  199. }
  200. }
  201. if (count($productInfoList) != count($ids)) {
  202. util::fail('存在无效商品');
  203. }
  204. } else {
  205. util::fail('花材不存在');
  206. }
  207. //供货商预订单最低公斤数要求和每公斤服务费
  208. $ghsInfo['kiloFee'] = 0;
  209. $ghsInfo['miniKilo'] = 0;
  210. $post['product'] = $productList;
  211. $packCost = 0;
  212. $post['packCost'] = $packCost;
  213. $post['sendCost'] = isset($post['sendCost']) && $post['sendCost'] > 0 ? $post['sendCost'] : 0;
  214. $respond = PurchaseService::createPurchase($post, $ghsInfo);
  215. if ($payMode == 0) {
  216. //欠款
  217. PurchaseService::debt($respond);
  218. } else {
  219. //线下支付
  220. PurchaseService::payAfter($respond, $payWay);
  221. $saleId = $respond->saleId ?? 0;
  222. $order = OrderClass::getById($saleId, true);
  223. if (empty($order)) {
  224. util::fail('没有找到订单');
  225. }
  226. OrderService::payAfter($order, $payWay, true);
  227. }
  228. $transaction->commit();
  229. $transactionFinished = true;
  230. ProductClass::clearLimitBuyRollbackSnapshot();
  231. util::success($respond);
  232. } catch (\Throwable $e) {
  233. if ($transaction->isActive) {
  234. $transaction->rollBack();
  235. }
  236. ProductClass::rollbackLimitBuySnapshot();
  237. $transactionFinished = true;
  238. util::fail();
  239. }
  240. }
  241. // 批发商的限购花材信息
  242. public function actionLimitBuyInfo()
  243. {
  244. $post = Yii::$app->request->post();
  245. $ghsId = $post['ghsId'] ?? 0;
  246. $list = $post['list'] ?? [];
  247. if (empty($ghsId)) {
  248. util::fail('缺少供货商');
  249. }
  250. if (empty($list) || !is_array($list)) {
  251. util::fail('请选择花材');
  252. }
  253. $ghsInfo = GhsClass::getById($ghsId);
  254. if (empty($ghsInfo)) {
  255. util::fail('没有找到供货商');
  256. }
  257. $customId = $ghsInfo['customId'] ?? 0;
  258. if (empty($customId)) {
  259. util::fail('没有找到客户');
  260. }
  261. $respond = ProductClass::getLimitBuyInfoByList($list, $customId);
  262. util::success($respond);
  263. }
  264. //生成采购单 ssh 2021.1.17
  265. public function actionCreateOrder()
  266. {
  267. $post = Yii::$app->request->post();
  268. $version = $post['version'] ?? 0;
  269. $direct = $post['direct'] ?? 0;
  270. //避免重复提交
  271. $adminId = $this->adminId;
  272. util::checkRepeatCommit($adminId, 3);
  273. //多颜色数据整理
  274. $colorItem = $post['xj'] ?? [];
  275. $newXj = [];
  276. if (!empty($colorItem)) {
  277. $colorData = json_decode($colorItem, true);
  278. if (!empty($colorData) && is_array($colorData)) {
  279. foreach ($colorData as $colorInfo) {
  280. $ptItemId = $colorInfo['ptItemId'] ?? 0;
  281. $colorList = $colorInfo['list'] ?? [];
  282. if (!empty($colorList)) {
  283. foreach ($colorList as $colorItemKey => $colorItem) {
  284. $newXj[$ptItemId][] = $colorItem;
  285. }
  286. }
  287. }
  288. }
  289. }
  290. $post['xj'] = $newXj;
  291. $ghsId = $post['ghsId'] ?? 0;
  292. //供货商
  293. $ghsInfo = GhsClass::getById($ghsId);
  294. if (empty($ghsInfo)) {
  295. util::fail('没有找到供货商');
  296. }
  297. $ghsShopId = $ghsInfo['shopId'] ?? 0;
  298. if (!empty($ghsInfo['mainId']) && $ghsInfo['mainId'] == $ghsInfo['ownMainId']) {
  299. util::fail('不能跟自己的店买花');
  300. }
  301. $connection = Yii::$app->db;
  302. $transaction = $connection->beginTransaction();
  303. $transactionFinished = false;
  304. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  305. if ($transactionFinished) {
  306. return;
  307. }
  308. ProductClass::rollbackLimitBuySnapshot();
  309. if ($transaction->isActive) {
  310. $transaction->rollBack();
  311. }
  312. });
  313. try {
  314. $post['book'] = $post['book'] ?? 0;
  315. $post['sjId'] = $this->sjId;
  316. $post['shopId'] = $this->shopId;
  317. $post['shopAdminId'] = $this->shopAdminId;
  318. $post['ghsId'] = $ghsId;
  319. $post['ghsName'] = $ghsInfo['name'] ?? '';
  320. $post['ghsMobile'] = $ghsInfo['mobile'] ?? '';
  321. $post['ghsAvatar'] = $ghsInfo['avatar'] ?? '';
  322. $post['ghsFullAddress'] = $ghsInfo['fullAddress'] ?? '';
  323. $customId = $ghsInfo['customId'] ?? 0;
  324. $custom = CustomClass::getById($customId, true);
  325. if (empty($custom)) {
  326. util::fail('用户信息缺失');
  327. }
  328. $post['customId'] = $customId;
  329. $shopAdmin = $this->shopAdmin ?? null;
  330. $name = $shopAdmin->name ?? '';
  331. $post['shopAdminName'] = $name;
  332. $post['mainId'] = $this->mainId;
  333. $product = $post['product'] ?? '';
  334. $productList = json_decode($product, true);
  335. //判断product数据是不是同个供货商的
  336. $ghsShopInfo = ShopClass::getById($ghsShopId, true);
  337. $ghsMainId = $ghsShopInfo->mainId ?? 0;
  338. $isOpen = ShopClass::isOpen($ghsShopInfo);
  339. $book = $post['book'] ?? 0;
  340. if ($isOpen == 0 && $book == 0) {
  341. util::fail('本店已休息,请选择其它门店');
  342. }
  343. if (isset($post['transType']) && $post['transType'] == 4) {
  344. if (isset($ghsShopInfo->pfLevel) && $ghsShopInfo->pfLevel == 1) {
  345. $notSameCity = PurchaseClass::notSameCity($this->shop, $ghsShopInfo);
  346. if (!$notSameCity) {
  347. util::fail('距离太远,不能选择同城配送');
  348. }
  349. }
  350. }
  351. if ($book == 1) {
  352. $sendTimeWant = isset($post['sendTimeWant']) && !empty($post['sendTimeWant']) ? $post['sendTimeWant'] : date("Y-m-d");
  353. $future = date("Y-m-d", strtotime('+2 day'));
  354. if (strtotime($sendTimeWant) < strtotime($future)) {
  355. //util::fail('请选择时间');
  356. }
  357. $nowTime = strtotime(date("Y-m-d"));
  358. if (strtotime($sendTimeWant) < $nowTime) {
  359. util::fail('不能选择过去时间');
  360. }
  361. }
  362. //收集客户要下单的花材数量
  363. $orderNum = [];
  364. $productCount = 0;
  365. foreach ($productList as $key => $product) {
  366. $bigNum = $product['bigNum'] ?? 0;
  367. $smallNum = $product['smallNum'] ?? 0;
  368. $pName = $product['name'] ?? '';
  369. if ($smallNum > 0) {
  370. util::fail($pName . '不能选小单位');
  371. }
  372. $productId = $product['productId'] ?? 0;
  373. $orderNum[$productId] = ['num' => $bigNum];
  374. $productCount += $bigNum;
  375. }
  376. $lackList = [];
  377. $changeList = [];
  378. $ids = array_unique(array_filter(array_column($productList, 'productId')));
  379. $productInfoList = ProductClass::getByIds($ids, null, 'id');
  380. if (!empty($productInfoList)) {
  381. $presellData = [];
  382. $nowTime = strtotime(date("Y-m-d"));
  383. foreach ($productInfoList as $currentInfo) {
  384. if (!isset($currentInfo['mainId']) || $currentInfo['mainId'] != $ghsMainId) {
  385. util::fail('只能选一家的商品,请清空重新选。');
  386. }
  387. $currentName = $currentInfo['name'] ?? '';
  388. if (isset($currentInfo['frontHide']) && $currentInfo['frontHide'] == 1) {
  389. //珑松珠海店,隐藏的商品,分享出去了也要能下单。644 是测试账号的mainId
  390. if (isset($currentInfo['mainId']) && in_array($currentInfo['mainId'], [14116, 644])) {
  391. //无操作
  392. } else {
  393. util::fail($currentName . ' 没有库存,请删除');
  394. }
  395. }
  396. $presell = $currentInfo['presell'] ?? 0;
  397. $presellData[] = $presell;
  398. if ($presell == 1) {
  399. if ($book == 1) {
  400. util::fail('预订时不能选择预售花材');
  401. } else {
  402. if (empty($post['sendTimeWant'])) {
  403. util::fail('请选择配送日期');
  404. }
  405. $sendTimeWant = $post['sendTimeWant'];
  406. if (strtotime($sendTimeWant) < $nowTime) {
  407. util::fail('不能选择过去时间');
  408. }
  409. $hasDateStr = $currentInfo['presellDate'] ?? [];
  410. $hasDate = explode(',', trim($hasDateStr));
  411. if (empty($hasDate)) {
  412. util::fail('预售日期有问题,请提醒门店');
  413. }
  414. if (!in_array(strtotime($sendTimeWant), $hasDate)) {
  415. util::fail("有预售花材在{$sendTimeWant}没到货");
  416. }
  417. $post['presell'] = 1;
  418. }
  419. }
  420. if ($version >= 10) {
  421. $stock = $currentInfo['stock'] ?? 0;
  422. $stock = floatval($stock);
  423. //会有0.5扎和2.5扎问题,所以要转成整数,不然会出严重问题 ssh 20250503
  424. $stock = intval($stock);
  425. $productId = $currentInfo['id'] ?? 0;
  426. $productName = $currentInfo['name'] ?? '';
  427. $num = $orderNum[$productId] && $orderNum[$productId]['num'] ? $orderNum[$productId]['num'] : 0;
  428. $num = floatval($num);
  429. if ($num > $stock) {
  430. $lackList[] = ['name' => $productName, 'stock' => $stock];
  431. $changeList[$productId] = $stock;
  432. }
  433. }
  434. }
  435. if (count($productInfoList) != count($ids)) {
  436. util::fail('存在无效商品');
  437. }
  438. $presellData = array_unique($presellData);
  439. if (count($presellData) > 1) {
  440. util::fail('预售和非预售花材不能一起下单');
  441. }
  442. if ($version >= 10) {
  443. if ($direct == 1) {
  444. //直接更换库存并提交
  445. $allNoStock = true;
  446. foreach ($productList as $pKey => $pVal) {
  447. $productId = $pVal['productId'] ?? 0;
  448. if (isset($changeList[$productId])) {
  449. $changeStock = $changeList[$productId];
  450. $productList[$pKey]['bigNum'] = $changeStock;
  451. }
  452. if ($productList[$pKey]['bigNum'] > 0) {
  453. $allNoStock = false;
  454. }
  455. if ($productList[$pKey]['bigNum'] <= 0) {
  456. unset($productList[$pKey]);
  457. }
  458. }
  459. if ($allNoStock) {
  460. util::fail('全部没库存了');
  461. }
  462. } else {
  463. //前台提示库存不足
  464. if (!empty($lackList)) {
  465. util::success(['lackList' => $lackList, 'hasLackError' => 1]);
  466. }
  467. }
  468. }
  469. } else {
  470. util::fail('花材不存在');
  471. }
  472. //供货商预订单最低公斤数要求和每公斤服务费
  473. $ghsInfo['kiloFee'] = $ghsShopInfo->kiloFee ?? 0;
  474. $ghsInfo['miniKilo'] = $ghsShopInfo->miniKilo ?? 0;
  475. $post['product'] = $productList;
  476. // xhShMethod 门店下单前保留花材合计,供后续 packCost 计算(pfLevel==0 分支会 unset itemTotalAmount)
  477. $shMethodItemAmount = $post['itemTotalAmount'] ?? 0;
  478. $sendType = $post['sendType'] ?? 0;
  479. $transType = $post['transType'] ?? 0;
  480. if ($sendType == dict::getDict('sendType', 'thirdSend')) {
  481. $shopExt = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,thirdSend,hcMap,hcFreeKm');
  482. if ($shopExt->thirdSend == 1) {
  483. util::fail('本店暂不能使用跑腿哦');
  484. }
  485. }
  486. if (isset($ghsShopInfo->pfLevel) && $ghsShopInfo->pfLevel == 1) {
  487. //昆明发货包装费和运费的计算
  488. $totalWeight = 0;
  489. $totalItemNum = 0;
  490. foreach ($productList as $itemData) {
  491. $bigNum = $itemData['bigNum'] ?? 0;
  492. $thisWeight = $itemData['weight'] ?? 0;
  493. $currentWeight = bcmul($thisWeight, $bigNum, 2);
  494. $totalWeight = bcadd($currentWeight, $totalWeight, 2);
  495. $totalItemNum = bcadd($totalItemNum, $bigNum, 2);
  496. }
  497. $totalItemNum = floatval($totalItemNum);
  498. $kmPackCost = PurchaseClass::getKmPackCost($ghsMainId);
  499. $packCost = 0;
  500. if (!empty($kmPackCost)) {
  501. foreach ($kmPackCost as $itemPack) {
  502. $kiloNum = $itemPack['num'] ?? 0;
  503. if ($kiloNum >= $totalWeight) {
  504. $packCost = $itemPack['amount'] ?? 0;
  505. break;
  506. }
  507. }
  508. if (isset($ghsInfo['mainId']) && $ghsInfo['mainId'] == 14499) {
  509. noticeUtil::push("总重量" . $totalWeight, '15280215347');
  510. }
  511. }
  512. if (isset($ghsInfo['mainId']) && $ghsInfo['mainId'] == 14499) {
  513. noticeUtil::push("走的pfLevel=1", '15280215347');
  514. }
  515. //同城配送和到店自取免打包费
  516. if ($transType == 4 || $transType == 5) {
  517. $packCost = 0;
  518. if (isset($ghsInfo['mainId']) && $ghsInfo['mainId'] == 14499) {
  519. noticeUtil::push("没有计算打包费原因:transType = 4 =5", '15280215347');
  520. }
  521. }
  522. //如果已经算过一次打包费和运费了,则不再费了
  523. $needAdd = \bizHd\shop\classes\ShopClass::needAddPackCost($ghsShopInfo, $customId, $sendType);
  524. if (!$needAdd) {
  525. $packCost = 0;
  526. if (isset($ghsInfo['mainId']) && $ghsInfo['mainId'] == 14499) {
  527. noticeUtil::push("没有计算打包费原因:已经算过一次了", '15280215347');
  528. }
  529. }
  530. $post['packCost'] = $packCost;
  531. $transCost = dict::getDict('transCost', null, null, $ghsShopInfo->mainId);
  532. $sendCost = 0;
  533. if (!empty($transCost)) {
  534. foreach ($transCost as $trans) {
  535. $sign = $trans['sign'] ?? 0;
  536. if ($sign == $transType) {
  537. if ($sign == 2) {
  538. //冷链物流
  539. $llOption = $trans['option'] ?? [];
  540. if (!empty($llOption)) {
  541. $largeInfo = end($llOption);
  542. $largeNum = $largeInfo['num'] ?? 0;
  543. $largeAmount = $largeInfo['amount'] ?? 0;
  544. $bs = intval($totalItemNum / $largeNum);
  545. if ($bs > 0) {
  546. $addSendCost = bcmul($bs, $largeAmount, 2);
  547. $sendCost = bcadd($sendCost, $addSendCost, 2);
  548. $subNum = bcmul($bs, $largeNum, 2);
  549. $subNum = floatval($subNum);
  550. $totalItemNum = bcsub($totalItemNum, $subNum, 2);
  551. $totalItemNum = floatval($totalItemNum);
  552. }
  553. foreach ($llOption as $miniItem) {
  554. if ($miniItem['num'] >= $totalItemNum) {
  555. $sendCost = bcadd($sendCost, $miniItem['amount'], 2);
  556. break;
  557. }
  558. }
  559. }
  560. } else {
  561. //其它物流
  562. $perKiloCost = $trans['perKiloCost'] ?? 0;
  563. $sendCost = bcmul($perKiloCost, $totalWeight, 3);
  564. $sendCost = round($sendCost, 2);
  565. }
  566. }
  567. }
  568. }
  569. //如果已经算过一次打包费和运费了,则不再费了
  570. $needAdd = \bizHd\shop\classes\ShopClass::needAddPackCost($ghsShopInfo, $customId, $sendType);
  571. if ($needAdd == false) {
  572. $sendCost = 0;
  573. }
  574. $post['sendCost'] = $sendCost;
  575. //标记为昆明到地方订单
  576. $post['localOrder'] = 1;
  577. } else {
  578. // xhShMethod 门店:下单前按配置写入不满最低消费时的附加包装费/运费,关键词 sh_method_area
  579. $newStatus = dict::getNewMethod($ghsShopId);
  580. if ($newStatus) {
  581. $shCurrentConfig = shMethodClass::getConfig($ghsShopId, $ghsMainId, $sendType);
  582. $shCurrentName = $shCurrentConfig['name'] ?? '';
  583. if (isset($shCurrentConfig['status']) && $shCurrentConfig['status'] == 0) {
  584. util::fail($shCurrentName . '已停用');
  585. }
  586. if ($sendType == dict::getDict('sendType', 'thirdSend')) {
  587. //如果是发跑腿
  588. // 生成随机订单号,不要跟原来的订单号混起来,跑腿-销售单-
  589. $prefix = 'PT-XSD-' . $this->mainId . '-';
  590. $orderSn = $prefix . round(microtime(true) * 1000);
  591. $calcType = $shCurrentConfig['calcType'] ?? 0;
  592. if ($calcType == 1) {
  593. //使用自定义计算费用
  594. $startKm = $shCurrentConfig['startKm'] ?? 0;
  595. $startPrice = $shCurrentConfig['startPrice'] ?? 0;
  596. $perKmPrice = $shCurrentConfig['perKmPrice'] ?? 0;//超出起步,每公里加收金额
  597. $changeRate = $shCurrentConfig['changeRate'] ?? 0;//负值时为降价百分比,正值时为涨价百分比
  598. if ($startKm <= 0 || $startPrice <= 0 || $perKmPrice <= 0) {
  599. noticeUtil::push("算运费失败,请更换配送方式 startKm {$startKm} startPrice {$startPrice} perKmPrice {$perKmPrice}", '15280215347');
  600. util::fail('算运费失败,请更换配送方式');
  601. }
  602. //计算客户到店的距离,骑电动车
  603. $distanceRespond = mapUtil::calcShopDistanceByEleBike($custom, $ghsShopInfo);
  604. $sendDistance = $distanceRespond['distanceKm'] ?? 0;
  605. if ($sendDistance <= 0) {
  606. util::fail('算运费失败,距离是0,请选到店自取');
  607. }
  608. // 计算运费逻辑
  609. $sendCost = $startPrice;
  610. if ($sendDistance > $startKm) {
  611. $extraDistance = bcsub($sendDistance, $startKm, 2);
  612. $extraCost = bcmul($extraDistance, $perKmPrice, 2);
  613. $sendCost = bcadd($sendCost, $extraCost, 2);
  614. }
  615. if ($changeRate != 0) {
  616. // 临时涨价/降价百分比
  617. $rate = bcadd(1, bcdiv($changeRate, 100, 4), 4);
  618. $sendCost = bcmul($sendCost, $rate, 2);
  619. }
  620. // 自定义计费也要套满减,否则确认页按规则免了 15 元、下单仍按起步价落库
  621. $distanceMeters = floatval($distanceRespond['distance'] ?? 0);
  622. if ($distanceMeters <= 0 && $sendDistance > 0) {
  623. $distanceMeters = floatval(bcmul($sendDistance, 1000, 2));
  624. }
  625. $discountRespond = DeliveryQuoteUtil::applyReduceRules(
  626. $shCurrentConfig,
  627. $sendCost,
  628. $distanceMeters,
  629. $shMethodItemAmount,
  630. $productCount
  631. );
  632. $sendCost = $discountRespond['sendCost'] ?? $sendCost;
  633. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $sendCost, 2);
  634. $post['sendDistance'] = $sendDistance;
  635. noticeUtil::push("自定义运费计算:" . $sendCost . "|" . $post['sendCost'] . " distanceMeters:" . $distanceMeters . " config:" . json_encode($shCurrentConfig), '15280215347');
  636. } else {
  637. // 使用 DeliveryQuoteUtil 获取配送报价
  638. try {
  639. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  640. 'productList' => $productList,
  641. 'deliveryPlatform' => $post['deliveryPlatform'],
  642. 'deliveryBracketContent' => $post['deliveryBracketContent'], // 平台多报价识别id
  643. 'ghsInfo' => $ghsInfo,
  644. 'custom' => $custom,
  645. 'order' => [
  646. 'orderSn' => $orderSn,
  647. 'goodsType' => 1, //商品类型:0 花束 1 花材
  648. 'itemTotalAmount' => $post['itemTotalAmount'] ?? 0,
  649. 'remark' => $post['remark'] ?? '',
  650. ],
  651. 'mainId' => $this->mainId,
  652. 'productCount' => $productCount,
  653. //当前配送方式
  654. 'shConfig' => $shCurrentConfig,
  655. ]);
  656. $sendCost = $quoteResult['sendCost'];
  657. $sendDistance = $quoteResult['sendDistance'];
  658. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $sendCost, 2);
  659. $post['sendDistance'] = $sendDistance;
  660. } catch (\Exception $e) {
  661. noticeUtil::push("计算跑腿费用出错了:" . $e->getMessage(), '15280215347');
  662. util::fail('下单失败,请选其他配送方式');
  663. }
  664. }
  665. } else {
  666. //如果是不是发跑腿,比如送货上门和发快递,则可能要收运费或打包费任一
  667. $shMethodBigNum = 0;
  668. foreach ($productList as $itemData) {
  669. $shMethodBigNum += floatval($itemData['bigNum'] ?? 0);
  670. }
  671. $additionalCosts = ShMethodClass::calcFee(
  672. $shCurrentConfig,
  673. $sendType,
  674. $shMethodItemAmount,
  675. $shMethodBigNum,
  676. $customId,
  677. $ghsInfo
  678. );
  679. // 如果产生了附加运费,与前面可能产生的 sendCost 进行累加或覆盖
  680. if ($additionalCosts['sendCost'] > 0) {
  681. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $additionalCosts['sendCost'], 2);
  682. }
  683. // 如果产生了附加包装费,覆盖前面赋值的 packCost。
  684. if ($additionalCosts['packCost'] > 0) {
  685. $post['packCost'] = $additionalCosts['packCost'];
  686. }
  687. }
  688. } else {
  689. //同城发货包装费和运费的计算
  690. $sendCost = 0;
  691. $sendDistance = 0;
  692. //特别注意,这边取供货商的shop信息
  693. $mapSet = ShopClass::hasIntraCity($ghsShopInfo);
  694. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  695. if ($sendType == dict::getDict('sendType', 'thirdSend')) {
  696. if ($openIntraCity == 2) {
  697. util::fail('不能使用跑腿');
  698. }
  699. if ($openIntraCity == 1) {
  700. // 生成随机订单号,不要跟原来的单号混起来,跑腿-销售单-
  701. $prefix = 'PT-XSD-' . $this->mainId . '-';
  702. $orderSn = $prefix . round(microtime(true) * 1000);
  703. // 使用 DeliveryQuoteUtil 获取配送报价
  704. try {
  705. if (empty($post['deliveryPlatform'])) {
  706. util::fail('请选择跑腿');
  707. }
  708. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  709. 'productList' => $productList,
  710. 'deliveryPlatform' => $post['deliveryPlatform'],
  711. 'deliveryBracketContent' => $post['deliveryBracketContent'], // 平台多报价识别id
  712. 'ghsInfo' => $ghsInfo,
  713. 'custom' => $custom,
  714. 'order' => [
  715. 'orderSn' => $orderSn,
  716. 'goodsType' => 1, //商品类型:0花束 1花材
  717. 'itemTotalAmount' => $post['itemTotalAmount'] ?? 0,
  718. 'remark' => $post['remark'] ?? '',
  719. ],
  720. 'mainId' => $this->mainId,
  721. 'productCount' => $productCount,
  722. ]);
  723. $sendCost = $quoteResult['sendCost'];
  724. $sendDistance = $quoteResult['sendDistance'];
  725. } catch (\Exception $e) {
  726. noticeUtil::push("计算跑腿费用出错了:" . $e->getMessage(), '15280215347');
  727. util::fail('下单失败,请选其他配送方式');
  728. }
  729. }
  730. }
  731. $post['sendCost'] = $sendCost;
  732. $post['sendDistance'] = $sendDistance;
  733. // 出车(0)、发快递(4)、发物流可以算包装费
  734. $packCost = 0;
  735. if (isset($ghsInfo['mainId']) && $ghsInfo['mainId'] == 14499) {
  736. noticeUtil::push("走的pfLevel=0", '15280215347');
  737. }
  738. $itemTotalAmount = $post['itemTotalAmount'] ?? 0;
  739. unset($post['itemTotalAmount']);
  740. // sendType == 4 要收包装费
  741. if ($sendType == 4) {
  742. $needAdd = \bizHd\shop\classes\ShopClass::needAddPackCost($ghsShopInfo, $customId, $sendType, $itemTotalAmount);
  743. if ($needAdd) {
  744. $packCost = $ghsShopInfo->packCost ?? 0;
  745. }
  746. }
  747. $post['packCost'] = $packCost;
  748. }
  749. }
  750. $respond = PurchaseService::createPurchase($post, $ghsInfo);
  751. $newStatus = dict::getNewMethod($ghsShopId);
  752. if ($newStatus) {
  753. // 使用 xhShMethod 配置校验配送限制,替代旧版门店硬编码规则,关键词 sh_method_area
  754. $shMethodError = ShMethodClass::checkLimit(
  755. $ghsShopId,
  756. $ghsMainId,
  757. $sendType,
  758. $respond->actPrice ?? 0,
  759. $respond->bigNum ?? 0,
  760. $post['packCost'] ?? 0,
  761. $post['sendCost'] ?? 0,
  762. $post['wlName'] ?? '',
  763. $customId,
  764. $ghsInfo
  765. );
  766. if ($shMethodError !== '') {
  767. $transaction->rollBack();
  768. util::fail($shMethodError);
  769. }
  770. } else {
  771. if ($sendType == 0) {
  772. if (getenv('YII_ENV') == 'production') {
  773. //杭州斗南鲜花批发部,满500,10公里内免费配送,满1000,20公里免费配送
  774. if ($ghsShopId == 4608) {
  775. if ($respond->actPrice < 500) {
  776. $transaction->rollBack();
  777. util::fail('满500元支持免费配送');
  778. }
  779. }
  780. //叶上花,满500元市区免费配送
  781. if ($ghsShopId == 4804) {
  782. if ($respond->actPrice < 500) {
  783. $transaction->rollBack();
  784. util::fail('满500元支持免费配送');
  785. }
  786. }
  787. //花悠星 国恋 勇记 万丽 陆丰暂时不支持免费配送
  788. if ($ghsShopId == 7687 || $ghsShopId == 7831 || $ghsShopId == 7778 || $ghsShopId == 12003 || $ghsShopId == 38128) {
  789. util::fail('暂不支持送货上门,请选其它配送方式!');
  790. }
  791. //广州鑫源花卉,选择送货上门必须选必选商品
  792. if ($ghsShopId == 12439) {
  793. $hasMust = array_intersect($ids, [3446945, 3446970, 3446973, 3446979, 3446995, 3447010, 3447023, 3459983, 4333184, 4317745, 1585738]);
  794. if (empty($hasMust)) {
  795. util::fail('请返回选择 必选商品');
  796. }
  797. }
  798. //情意花卉,必选品
  799. if ($ghsShopId == 100883) {
  800. $hasMust = array_intersect($ids, [5017957, 5036067, 5036089, 5036099, 5017958, 5036063, 5017948, 5035980, 5036073, 5036075, 5036076, 5036117, 5036118, 5017949, 5035979, 5035976, 5035928, 5035930, 5036061, 5035879]);
  801. if (empty($hasMust)) {
  802. util::fail('请返回选择 必选商品');
  803. }
  804. }
  805. //三明易批花
  806. if ($ghsShopId == 82200) {
  807. if ($respond->actPrice < 100 || $respond->bigNum < 15) {
  808. $hasMust = array_intersect($ids, [4283478]);
  809. if (empty($hasMust)) {
  810. util::fail('没满100元且15扎,请返回选运费');
  811. }
  812. }
  813. // 按当天计时,把 sendTimeWant 要限制在两天的时间范围之内
  814. $future = date("Y-m-d", strtotime('+2 day'));
  815. if (strtotime($respond->sendTimeWant) > strtotime($future)) {
  816. util::fail('配送日期只能选最近二天');
  817. }
  818. }
  819. if ($ghsShopId == 77703) {
  820. //天天鲜花思明店,暂时关闭送货上门
  821. if ($respond->sendType == 0) {
  822. //util::fail('节日暂停送货上门,请选到店自取');
  823. }
  824. }
  825. if ($ghsShopId == 86726) {
  826. //藏花林
  827. if ($respond->transType != 4 && $respond->transType != 5) {
  828. util::fail('请选同城配送或到店自取');
  829. }
  830. }
  831. }
  832. if (isset($ghsInfo['home'])) {
  833. if ($ghsInfo['home'] == 0) {
  834. util::fail('暂不支持送货上门,请选其它配送方式');
  835. }
  836. $homeAmount = $ghsInfo['homeAmount'] ? floatval($ghsInfo['homeAmount']) : 0;
  837. $homeNum = $ghsInfo['homeNum'] ? floatval($ghsInfo['homeNum']) : 0;
  838. if ($homeAmount > 0 && $homeAmount > $respond->actPrice) {
  839. util::fail("满{$homeAmount}元 可送货上门");
  840. }
  841. if ($homeNum > 0 && $homeNum > $respond->bigNum) {
  842. util::fail("满{$homeNum}扎 可送货上门");
  843. }
  844. }
  845. }
  846. if ($sendType == 2) {
  847. //温州易批花,跑腿,不满100,要选10元的补运费商品
  848. if ($ghsShopId == 91115) {
  849. if ($respond->actPrice < 100) {
  850. $transaction->rollBack();
  851. $hasMust = array_intersect($ids, [4449812, 4449811]);
  852. if (empty($hasMust)) {
  853. util::fail('不满100,必选商品 补运费10元');
  854. }
  855. }
  856. }
  857. }
  858. if ($sendType == 4) {
  859. //温州易批花,快递,不满100,要选10元的补运费商品
  860. if ($ghsShopId == 91115) {
  861. if ($respond->actPrice < 100) {
  862. $transaction->rollBack();
  863. $hasMust = array_intersect($ids, [4449812, 4449811]);
  864. if (empty($hasMust)) {
  865. util::fail('不满100,必选商品 补运费10元');
  866. }
  867. }
  868. }
  869. }
  870. if ($sendType == 3) {
  871. //温州易批花,物流,不满200,要选10元的补运费商品
  872. if ($ghsShopId == 91115) {
  873. if ($respond->actPrice < 200) {
  874. $transaction->rollBack();
  875. $hasMust = array_intersect($ids, [4449812, 4449811]);
  876. if (empty($hasMust)) {
  877. util::fail('不满200,必选商品 补运费10元');
  878. }
  879. }
  880. }
  881. }
  882. }
  883. $transaction->commit();
  884. $transactionFinished = true;
  885. ProductClass::clearLimitBuyRollbackSnapshot();
  886. util::success($respond);
  887. } catch (\Exception $e) {
  888. if ($transaction->isActive) {
  889. $transaction->rollBack();
  890. }
  891. ProductClass::rollbackLimitBuySnapshot();
  892. $transactionFinished = true;
  893. Yii::error($e->getMessage());
  894. util::fail();
  895. }
  896. }
  897. /**
  898. * 赊账支付
  899. * 职责:处理采购单延期支付(记欠款/赊账),更新采购单状态,并触发后续的自动收货、通知、在线打印、跑腿呼叫等业务流
  900. * 入参:GET 传参 orderSn (采购单号)
  901. * 返回:JSON 格式的采购单属性
  902. * 副作用:更新采购单、订单状态,增减花材库存并记录库存流水,更新客户及供货商的最后下单时间,发送外部通知和打印请求
  903. * 关键边界:
  904. * 1. 校验采购单及客户的赊账权限
  905. * 2. 优化:复用采购单实例,避免重复查询
  906. * 3. 优化:将自动确认收货(confirmTake)包裹在独立事务中,合并写操作,减少磁盘 I/O
  907. * 4. 优化:合并打印逻辑中的 ShopExt 查询及订单保存,减少数据库交互
  908. * 5. 优化:使用 updateByCondition 直接更新最后下单时间,避免先 SELECT 再 UPDATE
  909. */
  910. public function actionDebtPay()
  911. {
  912. $get = Yii::$app->request->get();
  913. $orderSn = $get['orderSn'] ?? 0;
  914. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  915. PurchaseService::valid($info, $this->shopId);
  916. //解决重复和并发提交
  917. $cacheKey = 'hd_debt_pay_' . $orderSn;
  918. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  919. if (!empty($has)) {
  920. util::fail('请稍等...');
  921. }
  922. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 5, 'has']);
  923. if ($info->status == 5) {
  924. util::fail('订单已取消');
  925. }
  926. if ($info->status != 1) {
  927. util::fail('订单不是待付款状态');
  928. }
  929. if ($info->book == 1) {
  930. util::fail('预售不能记欠款');
  931. }
  932. $ghsId = $info->ghsId;
  933. $ghs = GhsClass::getGhsInfo($ghsId);
  934. $customId = $ghs['customId'] ?? 0;
  935. $custom = CustomClass::getCustom($customId);
  936. if (empty($custom)) {
  937. util::fail('没有找到客户');
  938. }
  939. if (isset($custom['debt']) == false || $custom['debt'] == CustomClass::IS_DEBT_NO) {
  940. util::fail('请先申请赊账权限');
  941. }
  942. if (getenv('YII_ENV') == 'production') {
  943. //源花汇不允许客户自己下欠款单
  944. if ($ghs['mainId'] == 10536) {
  945. util::fail('暂未开通');
  946. }
  947. }
  948. $connection = Yii::$app->db;
  949. $transaction = $connection->beginTransaction();
  950. try {
  951. //延期支付
  952. PurchaseService::debt($info);
  953. $transaction->commit();
  954. if (isset($info->localOrder) && $info->localOrder == 1) {
  955. if ($info->transType != 5 && $info->transType != 4) {
  956. //昆明发货,客户算了一次打包费和运费,第二次就不再算了
  957. $current = date("Y_m_d");
  958. $key = 'ghs_custom_today_has_get_pack_cost_' . $current . '_' . $customId;
  959. Yii::$app->redis->executeCommand('SETEX', [$key, 86400, '1']);
  960. }
  961. } else {
  962. //标记当配送方式已收一次包装费/运费,只要有成功单就标记,后续不再重复要求门槛或加收费用
  963. $current = date("Y_m_d");
  964. if (isset($info->sendType)) {
  965. $key = 'ghs_custom_today_has_get_pack_cost_' . $info->sendType . '_' . $current . '_' . $customId;
  966. Yii::$app->redis->executeCommand('SETEX', [$key, 86400, '1']);
  967. // 兼容快递/送货/跑腿收运费或限制下单的情况
  968. $sendKey = 'ghs_custom_today_has_get_send_cost_' . $info->sendType . '_' . $current . '_' . $customId;
  969. Yii::$app->redis->executeCommand('SETEX', [$sendKey, 86400, '1']);
  970. }
  971. }
  972. // 复杂分支/关键逻辑:不是预订单,且供货商配置为直接完成流程,则自动确认收货。
  973. // 优化:复用已有的 $info 实例,避免重复查询;同时将自动确认收货包裹在独立事务中,合并批量写操作,减少磁盘 I/O。
  974. if (!empty($info)) {
  975. if (isset($info->book) && $info->book == 0) {
  976. $ghsShopId = $ghs['shopId'] ?? 0;
  977. $ext = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,orderFlow');
  978. if (!empty($ext) && intval($ext->orderFlow ?? 0) === 0) {
  979. $takeTransaction = Yii::$app->db->beginTransaction();
  980. try {
  981. PurchaseClass::confirmTake($info);
  982. $takeTransaction->commit();
  983. } catch (\Exception $takeEx) {
  984. $takeTransaction->rollBack();
  985. Yii::error("自动确认收货失败: " . $takeEx->getMessage());
  986. throw $takeEx;
  987. }
  988. }
  989. }
  990. }
  991. //app新订单通知
  992. $saleId = $info->saleId ?? 0;
  993. $order = OrderClass::getById($saleId, true);
  994. if (!empty($order)) {
  995. $shopId = $order->shopId ?? 0;
  996. $shop = ShopClass::getById($shopId, true);
  997. if (!empty($shop)) {
  998. //通知供货商
  999. GhsNotifyClass::newOrderNotify($saleId);
  1000. }
  1001. //订单生成时唤起在线打印
  1002. if (isset($order->needPrint) && $order->needPrint == dict::getDict('needPrint', 'need')) {
  1003. //有几个地方要同步去修改
  1004. if (getenv('YII_ENV') == 'production') {
  1005. //源花汇、盛丰不自动打小票,关键词mall_order_no_auto_print
  1006. $mallOrderNoPrint = [10536, 44282, 26374];
  1007. } else {
  1008. $mallOrderNoPrint = [];
  1009. }
  1010. if (!in_array($order->mainId, $mallOrderNoPrint)) {
  1011. // 复杂分支/关键逻辑:优化:只查询一次 $ext,合并 $order->save(),减少数据库交互
  1012. $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  1013. $hasPrintSn = isset($ext->printSn) && !empty($ext->printSn);
  1014. OrderClass::onlinePrint($order);
  1015. if ($hasPrintSn) {
  1016. $order->printNum += 1;
  1017. }
  1018. //花镜 打二次小票,有多处要修改搜索关键词tow_print
  1019. if (in_array($order->mainId, [76796])) {
  1020. OrderClass::onlinePrint($order);
  1021. if ($hasPrintSn) {
  1022. $order->printNum += 1;
  1023. }
  1024. }
  1025. if ($hasPrintSn) {
  1026. $order->save();
  1027. }
  1028. }
  1029. }
  1030. //付款成功之后呼叫跑腿,关键词 pay_after_call_pt,多处要同步修改
  1031. GhsDeliveryOrderClass::payAfter($order);
  1032. // 复杂分支/关键逻辑:优化:使用 updateByCondition 直接更新最后下单时间,避免先 SELECT 再 UPDATE 的性能开销
  1033. $customId = $order->customId ?? 0;
  1034. $ghsId = $order->ghsId ?? 0;
  1035. $date = date("Y-m-d H:i:s");
  1036. if ($customId > 0) {
  1037. CustomClass::updateByCondition(['id' => $customId], ['recentExpend' => $date]);
  1038. }
  1039. if ($ghsId > 0) {
  1040. GhsClass::updateByCondition(['id' => $ghsId], ['recentExpend' => $date]);
  1041. }
  1042. }
  1043. } catch (\Exception $e) {
  1044. $transaction->rollBack();
  1045. Yii::error("赊账支付失败原因:" . $e->getMessage());
  1046. util::fail('支付失败');
  1047. }
  1048. util::success($info->attributes);
  1049. }
  1050. /**
  1051. * 采购待支付页:客户 xhGhsCustom 净余额支付(并发重试 + 行锁)。
  1052. */
  1053. public function actionCustomBalancePay()
  1054. {
  1055. $post = Yii::$app->request->post();
  1056. $orderSn = $post['orderSn'] ?? '';
  1057. if (empty($orderSn)) {
  1058. util::fail('订单号无效');
  1059. }
  1060. $cacheKey = 'hd_custom_balance_pay_' . $orderSn;
  1061. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1062. if (!empty($has)) {
  1063. util::fail('请稍等...');
  1064. }
  1065. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 8, 'has']);
  1066. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1067. if (empty($info)) {
  1068. util::fail('没有找到采购单');
  1069. }
  1070. PurchaseService::valid($info, $this->shopId);
  1071. $deadline = $info->deadline ?? '';
  1072. if (!empty($deadline) && time() > strtotime($deadline)) {
  1073. util::fail('订单已失效了哦');
  1074. }
  1075. $ghsId = intval($info->ghsId ?? 0);
  1076. $ghs = GhsClass::getGhsInfo($ghsId);
  1077. try {
  1078. $result = util::runWithDbConcurrencyRetry(function () use ($orderSn) {
  1079. $connection = Yii::$app->db;
  1080. $transaction = $connection->beginTransaction();
  1081. try {
  1082. $purchase = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1083. $respond = PurchaseService::payByGhsCustomBalance($purchase);
  1084. $transaction->commit();
  1085. return $respond;
  1086. } catch (\Exception $exception) {
  1087. if ($transaction->isActive) {
  1088. $transaction->rollBack();
  1089. }
  1090. throw $exception;
  1091. }
  1092. });
  1093. $info = $result['purchase'];
  1094. $order = $result['saleOrder'] ?? null;
  1095. if (!empty($order)) {
  1096. if (isset($info->book) && $info->book == 0 && !empty($ghs)) {
  1097. $ghsShopId = $ghs['shopId'] ?? 0;
  1098. $ext = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,orderFlow');
  1099. if (!empty($ext) && intval($ext->orderFlow ?? 0) === 0) {
  1100. $cg = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1101. if (!empty($cg)) {
  1102. PurchaseClass::confirmTake($cg);
  1103. }
  1104. }
  1105. }
  1106. $shopId = $order->shopId ?? 0;
  1107. $shop = ShopClass::getById($shopId, true);
  1108. if (!empty($shop)) {
  1109. GhsNotifyClass::newOrderNotify($order->id ?? 0);
  1110. }
  1111. if (isset($order->needPrint) && $order->needPrint == dict::getDict('needPrint', 'need')) {
  1112. OrderClass::onlinePrint($order);
  1113. }
  1114. GhsDeliveryOrderClass::payAfter($order);
  1115. $customId = $order->customId ?? 0;
  1116. $custom = CustomClass::getById($customId, true);
  1117. $date = date('Y-m-d H:i:s');
  1118. if (!empty($custom)) {
  1119. $custom->recentExpend = $date;
  1120. $custom->save();
  1121. }
  1122. $orderGhsId = $order->ghsId ?? 0;
  1123. $orderGhs = GhsClass::getById($orderGhsId, true);
  1124. if (!empty($orderGhs)) {
  1125. $orderGhs->recentExpend = $date;
  1126. $orderGhs->save();
  1127. }
  1128. }
  1129. util::success($info->attributes);
  1130. } catch (\Exception $e) {
  1131. Yii::info('客户余额支付失败:' . $e->getMessage());
  1132. util::fail($e->getMessage() ?: '支付失败');
  1133. }
  1134. }
  1135. //余额支付 ssh 2021.1.24
  1136. public function actionBalancePay()
  1137. {
  1138. $shopAdmin = $this->shopAdmin;
  1139. if (isset($shopAdmin->super) == false || $shopAdmin->super != 1) {
  1140. util::fail('超管才能操作');
  1141. }
  1142. $get = Yii::$app->request->get();
  1143. $orderSn = $get['orderSn'] ?? 0;
  1144. $password = $get['password'] ?? '';
  1145. // 重新获取,不加密的用户数据
  1146. $admin = AdminClass::getById($this->adminId, true);
  1147. if (password_verify($password, $admin->payPassword) == false) {
  1148. util::fail('密码错误');
  1149. }
  1150. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1151. if (empty($info)) {
  1152. util::fail('没有找到采购单');
  1153. }
  1154. if ($info->status == 5) {
  1155. util::fail('订单已取消');
  1156. }
  1157. if ($info->status != 1) {
  1158. util::fail('订单不是待付款状态');
  1159. }
  1160. PurchaseService::valid($info, $this->shopId);
  1161. $connection = Yii::$app->db;
  1162. $transaction = $connection->beginTransaction();
  1163. try {
  1164. //余额支付
  1165. purchaseService::balancePay($info);
  1166. $transaction->commit();
  1167. } catch (\Exception $e) {
  1168. $transaction->rollBack();
  1169. util::fail('支付失败');
  1170. }
  1171. util::success($info->attributes);
  1172. }
  1173. //采购记录 ssh 2021.1.24
  1174. public function actionList()
  1175. {
  1176. $get = Yii::$app->request->get();
  1177. $where = ['shopId' => $this->shopId];
  1178. $searchTime = $get['searchTime'] ?? '';
  1179. if (!empty($searchTime)) {
  1180. $startTime = $get['startTime'] ?? '';
  1181. $endTime = $get['endTime'] ?? '';
  1182. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  1183. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1184. }
  1185. $ghsId = $get['ghsId'] ?? 0;
  1186. if (!empty($ghsId)) {
  1187. $where['ghsId'] = (int)$ghsId;
  1188. }
  1189. $status = $get['status'] ?? 0;
  1190. if (!empty($status)) {
  1191. $where['status'] = $status;
  1192. }
  1193. $respond = PurchaseService::getPurchaseList($where);
  1194. $respond['shop'] = $this->shop->attributes;
  1195. util::success($respond);
  1196. }
  1197. //获取合并采购单列表 ssh 20260519
  1198. public function actionMergeOrderList()
  1199. {
  1200. Yii::$app->params['pageSize'] = 9999;
  1201. $get = Yii::$app->request->get();
  1202. $mergeId = $get['mergeId'] ?? 0;
  1203. if (empty($mergeId)) {
  1204. util::fail('请选择采购单');
  1205. }
  1206. $mergeSn = CgMergeSnClass::getById($mergeId, true);
  1207. if (empty($mergeSn)) {
  1208. util::fail('请选择合并采购单');
  1209. }
  1210. $salt = $get['salt'] ?? '';
  1211. if (!empty($salt)) {
  1212. if (empty($mergeSn->salt) || $mergeSn->salt != $salt) {
  1213. util::fail('此单无法查看哦');
  1214. }
  1215. } else {
  1216. if (empty($this->shopId)) {
  1217. util::fail('暂时不能查看');
  1218. }
  1219. if ($mergeSn->mainId != $this->mainId) {
  1220. util::fail('此单无法查看哈');
  1221. }
  1222. }
  1223. $ghsId = $mergeSn->ghsId ?? 0;
  1224. $where = [
  1225. 'ghsId' => $ghsId,
  1226. 'mergeId' => $mergeId,
  1227. ];
  1228. $respond = PurchaseService::getPurchaseList($where);
  1229. $totalPrice = 0;
  1230. if (!empty($respond['list'])) {
  1231. foreach ($respond['list'] as $one) {
  1232. $actPrice = $one['actPrice'] ?? 0;
  1233. $totalPrice = bcadd($totalPrice, $actPrice, 2);
  1234. }
  1235. }
  1236. $totalPrice = floatval($totalPrice);
  1237. $respond['totalPrice'] = $totalPrice;
  1238. $respond['shop'] = !empty($this->shop) ? $this->shop->attributes : [];
  1239. util::success($respond);
  1240. }
  1241. //采购详情 ssh 2021.01.25
  1242. public function actionDetail()
  1243. {
  1244. $get = Yii::$app->request->get();
  1245. $id = $get['id'] ?? 0;
  1246. $info = PurchaseService::getInfo($id, true, true);
  1247. if (empty($info)) {
  1248. util::fail('没有找到采购单');
  1249. }
  1250. $salt = $get['salt'] ?? '';
  1251. if (!empty($salt)) {
  1252. if (!isset($info['salt']) || $info['salt'] != $salt) {
  1253. util::fail('无效采购单呢!');
  1254. }
  1255. } else {
  1256. if (!isset($info['mainId']) || $info['mainId'] != $this->mainId) {
  1257. //util::fail('采购单不能访问');
  1258. }
  1259. }
  1260. $customId = $info['customId'] ?? 0;
  1261. $custom = CustomClass::getById($customId);
  1262. $customName = $custom['name'] ?? '';
  1263. $customMobile = $custom['mobile'] ?? '';
  1264. $info['customName'] = $customName;
  1265. $info['customMobile'] = $customMobile;
  1266. $hasDebtPay = $custom['debt'] ?? 0;
  1267. $book = $info['book'] ?? 0;
  1268. $presell = $info['presell'] ?? 0;
  1269. //预售不能记欠款
  1270. if ($book == 1) {
  1271. $hasDebtPay = 0;
  1272. }
  1273. if ($presell == 1) {
  1274. $hasDebtPay = 0;
  1275. }
  1276. $shop = $this->shop;
  1277. $info['pfShopId'] = $shop->pfShopId ?? 0;
  1278. $info['hasDebtPay'] = $hasDebtPay;
  1279. // 待支付页展示 xhGhsCustom 净余额(正数=可支付余额),不再使用 main.balance
  1280. $info['balance'] = 0;
  1281. $info['customNetBalance'] = '0.00';
  1282. $info['showBalancePay'] = 0;
  1283. $info['ghsSalt'] = '';
  1284. $ghsId = intval($info['ghsId'] ?? 0);
  1285. if ($ghsId > 0) {
  1286. $ghsRow = GhsClass::getById($ghsId, true);
  1287. if (!empty($ghsRow)) {
  1288. $info['ghsSalt'] = $ghsRow->salt ?? '';
  1289. $ghsCustomId = intval($ghsRow->customId ?? 0);
  1290. if ($ghsCustomId > 0) {
  1291. $ghsCustom = CustomClass::getById($ghsCustomId, true);
  1292. if (!empty($ghsCustom)) {
  1293. $net = AccountMoneyClass::getNetBalanceFromRow($ghsCustom);
  1294. $info['customNetBalance'] = $net;
  1295. if (bccomp($net, '0', 2) > 0) {
  1296. $info['balance'] = floatval($net);
  1297. $info['showBalancePay'] = 1;
  1298. }
  1299. }
  1300. }
  1301. }
  1302. }
  1303. $getPayType = dict::getDict('getPayType');
  1304. $info['getPayType'] = $getPayType;
  1305. //获取售后条件
  1306. $ghsId = $info['ghsId'] ?? 0;
  1307. $ghsInfo = GhsClass::getById($ghsId, true);
  1308. if (empty($ghsInfo)) {
  1309. util::fail('没有找到供货商');
  1310. }
  1311. $info['afterSale'] = $ghsInfo->afterSale ?? 1;
  1312. //重要,客户看到的电话修改成门店的联系电话
  1313. $ghsShopId = $ghsInfo->shopId ?? 0;
  1314. $ghsShopInfo = ShopClass::getById($ghsShopId, true);
  1315. $info['ghsMobile'] = $ghsShopInfo->telephone ?? '';
  1316. $info['ghsMobile2'] = $ghsShopInfo->telephone2 ?? '';
  1317. $info['hasRenew'] = 1;
  1318. //如果是快捷开单,则不需要显示累计待结,因为商家经常把快捷开单的订单发给客户结账
  1319. $showForPay = 1;
  1320. if ($ghsShopInfo->skCustomId == $info['customId']) {
  1321. $showForPay = 0;
  1322. }
  1323. $info['showForPay'] = $showForPay;
  1324. //冲销单详情页展示"原单"入口:如果当前采购单本身就是一张冲销单(forward==1),
  1325. //通过 xhCg.saleId(对应xhGhsOrder.id) 反查 xhGhsOrderForward 关联记录,
  1326. //拿到原销售单id后再取其 purchaseId 得到花店侧原采购单id,供前端跳转查看原单。ssh 冲销单功能
  1327. $forward = $info['forward'] ?? 0;
  1328. if ($forward == 1) {
  1329. $saleId = $info['saleId'] ?? 0;
  1330. if (!empty($saleId)) {
  1331. $relate = OrderForwardClass::getByForwardOrderId($saleId);
  1332. if (!empty($relate)) {
  1333. $relateOrder = OrderClass::getById($relate['orderId'], true);
  1334. if (!empty($relateOrder)) {
  1335. $info['relateCgId'] = $relateOrder->purchaseId ?? 0;
  1336. $info['relateOrderSn'] = $relate['orderSn'] ?? '';
  1337. }
  1338. }
  1339. }
  1340. }
  1341. util::success($info);
  1342. }
  1343. /**
  1344. * 按采购单查询关联的冲销记录,供 hdApp 售后记录页展示"冲销记录" ssh 冲销单功能
  1345. * xhCg.saleId 指向对应的批发销售单(xhGhsOrder.id),冲销关联记录统一存在 xhGhsOrderForward 表,
  1346. * 花店和供货商两端共用同一张表,这里直接跨命名空间复用 bizGhs\order\classes\OrderForwardClass 查询
  1347. */
  1348. public function actionGetForwardListByOrder()
  1349. {
  1350. $get = Yii::$app->request->get();
  1351. $id = $get['id'] ?? 0;
  1352. $cg = PurchaseClass::getById($id, true);
  1353. if (empty($cg)) {
  1354. util::fail('没有找到采购单');
  1355. }
  1356. if ($cg->mainId != $this->mainId) {
  1357. util::fail('无权查看');
  1358. }
  1359. $saleId = $cg->saleId ?? 0;
  1360. if (empty($saleId)) {
  1361. util::success(['list' => []]);
  1362. }
  1363. $list = OrderForwardClass::getByOrderId($saleId);
  1364. if (empty($list)) {
  1365. util::success(['list' => []]);
  1366. }
  1367. $forwardOrderIds = array_unique(array_filter(array_column($list, 'forwardOrderId')));
  1368. //冲销单在花店侧对应的采购单id(purchaseId),用于点击跳转到 hdApp 的采购单详情
  1369. $forwardOrderInfo = empty($forwardOrderIds) ? [] : OrderClass::getByIds($forwardOrderIds, null, 'id');
  1370. $data = [];
  1371. foreach ($list as $row) {
  1372. $forwardOrder = $forwardOrderInfo[$row['forwardOrderId']] ?? [];
  1373. $data[] = [
  1374. 'forwardCgId' => $forwardOrder['purchaseId'] ?? 0,
  1375. 'forwardOrderSn' => $row['forwardOrderSn'],
  1376. 'forwardPrice' => $row['forwardPrice'],
  1377. 'addTime' => $row['addTime'],
  1378. 'forwardStock' => $forwardOrder['forwardStock'] ?? 1,
  1379. ];
  1380. }
  1381. util::success(['list' => $data]);
  1382. }
  1383. //可用的支付方式 ssh 2021.1.25
  1384. public function actionPayWay()
  1385. {
  1386. $button = [
  1387. ['type' => 'wxPay', 'show' => 1, 'disable' => 1],
  1388. ['type' => 'debtPay', 'show' => 1, 'disable' => 0],
  1389. ['type' => 'balancePay', 'show' => 1, 'disable' => 0],
  1390. ];
  1391. util::success(['button' => $button]);
  1392. }
  1393. //待结款明细 ssh 2021.1.26
  1394. public function actionDebtList()
  1395. {
  1396. $get = Yii::$app->request->get();
  1397. $id = $get['id'] ?? 0;
  1398. $salt = $get['salt'] ?? '';
  1399. $info = GhsClass::getGhsInfo($id);
  1400. if (!empty($salt)) {
  1401. if (!isset($info['salt']) || $info['salt'] != $salt) {
  1402. util::fail('供货商出错了');
  1403. }
  1404. } else {
  1405. if (!isset($info['ownShopId']) || $info['ownShopId'] != $this->shopId) {
  1406. util::fail('错误的供货商.');
  1407. }
  1408. }
  1409. $where = ['ghsId' => $id, 'debt' => PurchaseClass::DEBT_YES];
  1410. $searchTime = $get['searchTime'] ?? '';
  1411. if (!empty($searchTime)) {
  1412. $startTime = $get['startTime'] ?? '';
  1413. $endTime = $get['endTime'] ?? '';
  1414. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  1415. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1416. }
  1417. $respond = PurchaseService::getDebtList($where);
  1418. util::success($respond);
  1419. }
  1420. //支付宝支付 ssh 2021.4.11
  1421. public function actionAliPay()
  1422. {
  1423. ini_set('date.timezone', 'Asia/Shanghai');
  1424. $post = Yii::$app->request->post();
  1425. //默认是支付宝支付
  1426. $payWay = $post['payWay'] ?? 1;
  1427. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1428. $order = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1429. if (empty($order)) {
  1430. util::fail('订单号无效');
  1431. }
  1432. if ($order->status == 5) {
  1433. util::fail('订单已取消');
  1434. }
  1435. if ($order->status != 1) {
  1436. util::fail('订单不是待付款状态');
  1437. }
  1438. $deadline = $order->deadline;
  1439. $current = time();
  1440. if (($current + 50) > strtotime($deadline)) {
  1441. util::fail('订单已失效,请重新下单');
  1442. }
  1443. $ghsId = $order->ghsId ?? 0;
  1444. $ghs = GhsClass::getById($ghsId, true);
  1445. if (empty($ghs)) {
  1446. util::fail('没有供货商信息');
  1447. }
  1448. $ghsShopId = $ghs->shopId ?? 0;
  1449. $ghsShop = ShopClass::getById($ghsShopId, true);
  1450. if (empty($ghsShop)) {
  1451. util::fail('没有供货商门店信息');
  1452. }
  1453. if (isset($ghsShop->lklSjNo) && empty($ghsShop->lklSjNo)) {
  1454. util::fail('商家支付功能未开通');
  1455. }
  1456. //避免重复提交
  1457. util::checkRepeatCommit($orderSn, 8);
  1458. //已经唤起过支付了,根据拉卡拉的规则,需要生成新的订单号
  1459. if ($order->changePrice == 2) {
  1460. $oldOrderSn = $orderSn;
  1461. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1462. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1463. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1464. $params = [
  1465. 'appid' => 'OP00002119',
  1466. 'serial_no' => '018b08cfddbd',
  1467. 'merchant_no' => $ghsShop->lklSjNo,
  1468. 'term_no' => $ghsShop->lklScanTermNo,
  1469. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1470. 'lklCertificatePath' => $lklCertificatePath,
  1471. ];
  1472. $laResource = new Lakala($params);
  1473. $closeParams = [
  1474. 'orderSn' => $oldOrderSn,
  1475. ];
  1476. $response = $laResource->cashClose($closeParams);
  1477. if (isset($response['code']) == false || $response['code'] != '000000') {
  1478. $msg = $response['msg'] ?? '';
  1479. $code = $response['code'] ?? 0;
  1480. if (!in_array($code, ['000091'])) {
  1481. noticeUtil::push('注意花店买花更换单号:' . $oldOrderSn . ',关单没有成功(收银台-支付宝),' . $msg, '15280215347');
  1482. }
  1483. }
  1484. $shopId = $order->shopId ?? 0;
  1485. $mainId = $order->mainId ?? 0;
  1486. $customId = $order->customId ?? 0;
  1487. $ghsId = $order->ghsId ?? 0;
  1488. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'customId' => $customId, 'ghsId' => $ghsId];
  1489. $newOrderSn = orderSn::getPurchaseSn($snData);
  1490. $orderSn = $newOrderSn;
  1491. $order->orderSn = $newOrderSn;
  1492. $order->save();
  1493. PurchaseItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $newOrderSn]);
  1494. }
  1495. $order->changePrice = 2;
  1496. $order->save();
  1497. $ghsShopName = $ghsShop->shopName ?? '';
  1498. //要带上哪个店的,这样才知道客户下的单是哪个店的,客户很多有多家店
  1499. $name = $ghsShopName . " 花材 " . $orderSn;
  1500. $totalFee = $order->realPrice;
  1501. $purchaseCapital = dict::getDict('capitalType', 'xhPurchase', 'id');
  1502. $ghsId = $order->ghsId ?? 0;
  1503. $ghs = GhsClass::getById($ghsId, true);
  1504. if (empty($ghs)) {
  1505. util::fail('没有供货商信息');
  1506. }
  1507. $ghsShopId = $ghs->shopId ?? 0;
  1508. $ghsShop = ShopClass::getById($ghsShopId, true);
  1509. if (empty($ghsShop)) {
  1510. util::fail('没有供货商门店信息');
  1511. }
  1512. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1513. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1514. $params = [
  1515. 'appid' => 'OP00002119',
  1516. 'serial_no' => '018b08cfddbd',
  1517. 'merchant_no' => $ghsShop->lklSjNo,
  1518. 'term_no' => $ghsShop->lklB2BTermNo,
  1519. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1520. 'lklCertificatePath' => $lklCertificatePath,
  1521. ];
  1522. $laResource = new Lakala($params);
  1523. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/cash-pay-callback";
  1524. $wxParams = [
  1525. 'orderSn' => $orderSn,
  1526. 'amount' => $totalFee,
  1527. 'capitalType' => $purchaseCapital,
  1528. 'notifyUrl' => $notifyUrl,
  1529. 'subject' => $name,
  1530. 'payWay' => $payWay,
  1531. ];
  1532. $response = $laResource->cashierPay($wxParams);
  1533. if (isset($response['code']) == false || $response['code'] != '000000') {
  1534. $errMsg = $response['msg'] ?? '';
  1535. noticeUtil::push('编号AA90:' . $errMsg, '15280215347');
  1536. util::fail('发起支付失败');
  1537. }
  1538. $counter_url = $response['resp_data']['counter_url'] ? $response['resp_data']['counter_url'] : '';
  1539. $hasRenew = $ghsShop->hasRenew ?? 0;
  1540. $new = [
  1541. 'payUrl' => $counter_url,
  1542. 'orderSn' => $orderSn,
  1543. 'hasRenew' => 1,
  1544. ];
  1545. util::success($new);
  1546. }
  1547. //微信支付 ssh 2021.4.11
  1548. public function actionWxPay()
  1549. {
  1550. ini_set('date.timezone', 'Asia/Shanghai');
  1551. $post = Yii::$app->request->post();
  1552. $couponId = $post['couponId'] ?? 0;
  1553. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1554. $order = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1555. if (empty($order)) {
  1556. util::fail('订单号无效');
  1557. }
  1558. if ($order->status == 5) {
  1559. util::fail('订单已取消');
  1560. }
  1561. if ($order->status != 1) {
  1562. util::fail('订单不是待付款状态');
  1563. }
  1564. $deadline = $order->deadline;
  1565. $current = time();
  1566. if (($current + 50) > strtotime($deadline)) {
  1567. util::fail('订单已失效,请重新下单');
  1568. }
  1569. //避免重复提交
  1570. util::checkRepeatCommit($orderSn, 8);
  1571. $ghsId = $order->ghsId ?? 0;
  1572. $ghs = GhsClass::getById($ghsId, true);
  1573. if (empty($ghs)) {
  1574. util::fail('没有供货商信息');
  1575. }
  1576. $ghsShopId = $ghs->shopId ?? 0;
  1577. $ghsShop = ShopClass::getById($ghsShopId, true);
  1578. if (empty($ghsShop)) {
  1579. util::fail('没有供货商门店信息');
  1580. }
  1581. if (isset($ghsShop->lklSjNo) && empty($ghsShop->lklSjNo)) {
  1582. util::fail('商家支付功能未开通');
  1583. }
  1584. //已经唤起过微信支付了,根据拉卡拉的规则,需要生成新的订单号
  1585. if ($order->changePrice == 2) {
  1586. $oldOrderSn = $orderSn;
  1587. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1588. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1589. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1590. $params = [
  1591. 'appid' => 'OP00002119',
  1592. 'serial_no' => '018b08cfddbd',
  1593. 'merchant_no' => $ghsShop->lklSjNo,
  1594. 'term_no' => $ghsShop->lklScanTermNo,
  1595. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1596. 'lklCertificatePath' => $lklCertificatePath,
  1597. ];
  1598. $laResource = new Lakala($params);
  1599. $closeParams = [
  1600. 'orderSn' => $oldOrderSn,
  1601. ];
  1602. $response = $laResource->close($closeParams);
  1603. if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
  1604. $msg = $response['msg'] ?? '';
  1605. $code = $response['code'] ?? 0;
  1606. if (!in_array($code, ['BBS11114'])) {
  1607. noticeUtil::push('重点注意,花店买花更换单号没有成功,单号:' . $oldOrderSn . ',关单没有成功,' . $msg . $code, '15280215347');
  1608. util::fail('出错了,请重新下单');
  1609. }
  1610. }
  1611. $shopId = $order->shopId ?? 0;
  1612. $mainId = $order->mainId ?? 0;
  1613. $customId = $order->customId ?? 0;
  1614. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'customId' => $customId, 'ghsId' => $ghsId];
  1615. $newOrderSn = orderSn::getPurchaseSn($snData);
  1616. $orderSn = $newOrderSn;
  1617. $order->orderSn = $newOrderSn;
  1618. $order->save();
  1619. PurchaseItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $newOrderSn]);
  1620. }
  1621. $id = $order->id;
  1622. $order->changePrice = 2;
  1623. $order->save();
  1624. $ghsShopName = $ghsShop->shopName ?? '';
  1625. //要带上哪个店的,这样才知道客户下的单是哪个店的,客户很多有多家店
  1626. $name = $ghsShopName . " 花材 " . $orderSn;
  1627. $totalFee = $order->realPrice;
  1628. $openId = '';
  1629. if (isset($post['currentMiniOpenId']) && !empty($post['currentMiniOpenId'])) {
  1630. $openId = $post['currentMiniOpenId'];
  1631. //noticeUtil::push('花店采购下单时,通过前端获取了openId:' . $openId, '15280215347');
  1632. }
  1633. if (empty($openId)) {
  1634. if (isset($this->admin) && !empty($this->admin)) {
  1635. if (isset($this->admin->miniOpenId) && !empty($this->admin->miniOpenId)) {
  1636. $openId = $this->admin->miniOpenId;
  1637. noticeUtil::push('花店采购下单时,通过数据库获取了openId:' . $openId, '15280215347');
  1638. }
  1639. }
  1640. }
  1641. if (empty($openId)) {
  1642. $currentShopId = $order->shopId ?? 0;
  1643. $currentShop = ShopClass::getById($currentShopId, true);
  1644. $currentShopName = $currentShop->merchantName . ' ' . $currentShop->shopName;
  1645. $currentMobile = $currentShop->mobile ?? '';
  1646. noticeUtil::push("花店采购时,发现没有openId,请跟进是否采购成功。{$currentShopName} {$currentMobile}", '15280215347');
  1647. util::success(['hasError' => 1, 'hasNoMiniOpenId' => 1]);
  1648. }
  1649. $purchaseCapital = dict::getDict('capitalType', 'xhPurchase', 'id');
  1650. //花卉宝代为申请的微信支付
  1651. $merchantExtend = WxOpenClass::getWxInfo();
  1652. if (empty($ghsShop->lklSjNo)) {
  1653. noticeUtil::push('编号31505:单号:' . $orderSn . ' 商家没有开通收款功能:' . $ghsShopName, '15280215347');
  1654. util::fail('商家未开通支付功能');
  1655. }
  1656. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1657. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1658. $params = [
  1659. 'appid' => 'OP00002119',
  1660. 'serial_no' => '018b08cfddbd',
  1661. 'merchant_no' => $ghsShop->lklSjNo,
  1662. 'term_no' => $ghsShop->lklScanTermNo,
  1663. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1664. 'lklCertificatePath' => $lklCertificatePath,
  1665. ];
  1666. $laResource = new Lakala($params);
  1667. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  1668. $wxParams = [
  1669. 'orderSn' => $orderSn,
  1670. 'amount' => $totalFee,
  1671. 'capitalType' => $purchaseCapital,
  1672. 'notifyUrl' => $notifyUrl,
  1673. 'wxAppId' => $merchantExtend['miniAppId'],
  1674. 'openId' => $openId,
  1675. 'subject' => $name,
  1676. 'couponId' => $couponId,
  1677. ];
  1678. $response = $laResource->driveWxPay($wxParams);
  1679. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1680. $errMsg = $response['msg'] ?? '';
  1681. noticeUtil::push('编号129680931:' . $errMsg . ' 单号:' . $orderSn . ' ' . $ghsShopName, '15280215347');
  1682. util::fail('支付失败');
  1683. }
  1684. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  1685. $appId = $newParams['app_id'] ?? '';
  1686. $nonceStr = $newParams['nonce_str'] ?? '';
  1687. $paySign = $newParams['pay_sign'] ?? '';
  1688. $package = $newParams['package'] ?? '';
  1689. $signType = $newParams['sign_type'] ?? '';
  1690. $timeStamp = $newParams['time_stamp'] ?? '';
  1691. $new = [
  1692. 'id' => $id,
  1693. 'appId' => $appId,
  1694. 'nonceStr' => $nonceStr,
  1695. 'paySign' => $paySign,
  1696. 'package' => $package,
  1697. 'signType' => $signType,
  1698. 'timeStamp' => $timeStamp,
  1699. 'orderSn' => $orderSn,
  1700. ];
  1701. util::success($new);
  1702. }
  1703. //计算运费 ssh 20221003
  1704. public function actionFreight()
  1705. {
  1706. $get = Yii::$app->request->get();
  1707. $shop = $this->shop;
  1708. $ghsId = $get['ghsId'] ?? 0;
  1709. $ghs = GhsClass::getById($ghsId, true);
  1710. if (empty($ghs)) {
  1711. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1712. }
  1713. $ghsShopId = $ghs->shopId ?? 0;
  1714. $ghsShop = ShopClass::getById($ghsShopId, true);
  1715. if (empty($ghsShop)) {
  1716. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1717. }
  1718. $customId = $ghs->customId ?? 0;
  1719. $custom = CustomClass::getById($customId, true);
  1720. if (empty($custom)) {
  1721. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1722. }
  1723. $weight = $get['weight'] ?? 0;
  1724. if (empty($weight)) {
  1725. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1726. }
  1727. $respond = PurchaseClass::getDistanceFee($shop, $ghsShop, $weight, $custom);
  1728. util::success($respond);
  1729. }
  1730. //运费计算 lqh 2021.4.12 暂时返回固定值
  1731. public function actionFreight2()
  1732. {
  1733. //lqh 2021.6.25 运费固定返回0
  1734. util::success(['sedCost' => 0]);
  1735. }
  1736. }