PurchaseController.php 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  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'] . " 数量:{$productCount} 金额:{$shMethodItemAmount} 距离:" . $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. // 标记附加费锁定:自然日 key + 实收时的间隔时间戳
  963. if (isset($info->sendType)) {
  964. ShMethodClass::markFeeStateAfterPurchaseSuccess(
  965. $customId,
  966. $info->sendType,
  967. $info->sendCost ?? 0,
  968. $info->packCost ?? 0
  969. );
  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. $printReturn = OrderClass::onlinePrint($order);
  1113. $printSn = $printReturn['printSn'] ?? '';
  1114. if (!empty($printSn)) {
  1115. $order->printNum += 1;
  1116. $order->save();
  1117. }
  1118. }
  1119. GhsDeliveryOrderClass::payAfter($order);
  1120. $customId = $order->customId ?? 0;
  1121. $custom = CustomClass::getById($customId, true);
  1122. $date = date('Y-m-d H:i:s');
  1123. if (!empty($custom)) {
  1124. $custom->recentExpend = $date;
  1125. $custom->save();
  1126. }
  1127. $orderGhsId = $order->ghsId ?? 0;
  1128. $orderGhs = GhsClass::getById($orderGhsId, true);
  1129. if (!empty($orderGhs)) {
  1130. $orderGhs->recentExpend = $date;
  1131. $orderGhs->save();
  1132. }
  1133. }
  1134. util::success($info->attributes);
  1135. } catch (\Exception $e) {
  1136. Yii::info('客户余额支付失败:' . $e->getMessage());
  1137. util::fail($e->getMessage() ?: '支付失败');
  1138. }
  1139. }
  1140. //余额支付 ssh 2021.1.24
  1141. public function actionBalancePay()
  1142. {
  1143. $shopAdmin = $this->shopAdmin;
  1144. if (isset($shopAdmin->super) == false || $shopAdmin->super != 1) {
  1145. util::fail('超管才能操作');
  1146. }
  1147. $get = Yii::$app->request->get();
  1148. $orderSn = $get['orderSn'] ?? 0;
  1149. $password = $get['password'] ?? '';
  1150. // 重新获取,不加密的用户数据
  1151. $admin = AdminClass::getById($this->adminId, true);
  1152. if (password_verify($password, $admin->payPassword) == false) {
  1153. util::fail('密码错误');
  1154. }
  1155. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1156. if (empty($info)) {
  1157. util::fail('没有找到采购单');
  1158. }
  1159. if ($info->status == 5) {
  1160. util::fail('订单已取消');
  1161. }
  1162. if ($info->status != 1) {
  1163. util::fail('订单不是待付款状态');
  1164. }
  1165. PurchaseService::valid($info, $this->shopId);
  1166. $connection = Yii::$app->db;
  1167. $transaction = $connection->beginTransaction();
  1168. try {
  1169. //余额支付
  1170. purchaseService::balancePay($info);
  1171. $transaction->commit();
  1172. } catch (\Exception $e) {
  1173. $transaction->rollBack();
  1174. util::fail('支付失败');
  1175. }
  1176. util::success($info->attributes);
  1177. }
  1178. //采购记录 ssh 2021.1.24
  1179. public function actionList()
  1180. {
  1181. $get = Yii::$app->request->get();
  1182. $where = ['shopId' => $this->shopId];
  1183. $searchTime = $get['searchTime'] ?? '';
  1184. if (!empty($searchTime)) {
  1185. $startTime = $get['startTime'] ?? '';
  1186. $endTime = $get['endTime'] ?? '';
  1187. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  1188. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1189. }
  1190. $ghsId = $get['ghsId'] ?? 0;
  1191. if (!empty($ghsId)) {
  1192. $where['ghsId'] = (int)$ghsId;
  1193. }
  1194. $status = $get['status'] ?? 0;
  1195. if (!empty($status)) {
  1196. $where['status'] = $status;
  1197. }
  1198. $respond = PurchaseService::getPurchaseList($where);
  1199. $respond['shop'] = $this->shop->attributes;
  1200. util::success($respond);
  1201. }
  1202. //获取合并采购单列表 ssh 20260519
  1203. public function actionMergeOrderList()
  1204. {
  1205. Yii::$app->params['pageSize'] = 9999;
  1206. $get = Yii::$app->request->get();
  1207. $mergeId = $get['mergeId'] ?? 0;
  1208. if (empty($mergeId)) {
  1209. util::fail('请选择采购单');
  1210. }
  1211. $mergeSn = CgMergeSnClass::getById($mergeId, true);
  1212. if (empty($mergeSn)) {
  1213. util::fail('请选择合并采购单');
  1214. }
  1215. $salt = $get['salt'] ?? '';
  1216. if (!empty($salt)) {
  1217. if (empty($mergeSn->salt) || $mergeSn->salt != $salt) {
  1218. util::fail('此单无法查看哦');
  1219. }
  1220. } else {
  1221. if (empty($this->shopId)) {
  1222. util::fail('暂时不能查看');
  1223. }
  1224. if ($mergeSn->mainId != $this->mainId) {
  1225. util::fail('此单无法查看哈');
  1226. }
  1227. }
  1228. $ghsId = $mergeSn->ghsId ?? 0;
  1229. $where = [
  1230. 'ghsId' => $ghsId,
  1231. 'mergeId' => $mergeId,
  1232. ];
  1233. $respond = PurchaseService::getPurchaseList($where);
  1234. $totalPrice = 0;
  1235. if (!empty($respond['list'])) {
  1236. foreach ($respond['list'] as $one) {
  1237. $actPrice = $one['actPrice'] ?? 0;
  1238. $totalPrice = bcadd($totalPrice, $actPrice, 2);
  1239. }
  1240. }
  1241. $totalPrice = floatval($totalPrice);
  1242. $respond['totalPrice'] = $totalPrice;
  1243. $respond['shop'] = !empty($this->shop) ? $this->shop->attributes : [];
  1244. util::success($respond);
  1245. }
  1246. //采购详情 ssh 2021.01.25
  1247. public function actionDetail()
  1248. {
  1249. $get = Yii::$app->request->get();
  1250. $id = $get['id'] ?? 0;
  1251. $info = PurchaseService::getInfo($id, true, true);
  1252. if (empty($info)) {
  1253. util::fail('没有找到采购单');
  1254. }
  1255. $salt = $get['salt'] ?? '';
  1256. if (!empty($salt)) {
  1257. if (!isset($info['salt']) || $info['salt'] != $salt) {
  1258. util::fail('无效采购单呢!');
  1259. }
  1260. } else {
  1261. if (!isset($info['mainId']) || $info['mainId'] != $this->mainId) {
  1262. //util::fail('采购单不能访问');
  1263. }
  1264. }
  1265. $customId = $info['customId'] ?? 0;
  1266. $custom = CustomClass::getById($customId);
  1267. $customName = $custom['name'] ?? '';
  1268. $customMobile = $custom['mobile'] ?? '';
  1269. $info['customName'] = $customName;
  1270. $info['customMobile'] = $customMobile;
  1271. $hasDebtPay = $custom['debt'] ?? 0;
  1272. $book = $info['book'] ?? 0;
  1273. $presell = $info['presell'] ?? 0;
  1274. //预售不能记欠款
  1275. if ($book == 1) {
  1276. $hasDebtPay = 0;
  1277. }
  1278. if ($presell == 1) {
  1279. $hasDebtPay = 0;
  1280. }
  1281. $shop = $this->shop;
  1282. $info['pfShopId'] = $shop->pfShopId ?? 0;
  1283. $info['hasDebtPay'] = $hasDebtPay;
  1284. // 待支付页展示 xhGhsCustom 净余额(正数=可支付余额),不再使用 main.balance
  1285. $info['balance'] = 0;
  1286. $info['customNetBalance'] = '0.00';
  1287. $info['showBalancePay'] = 0;
  1288. $info['ghsSalt'] = '';
  1289. $ghsId = intval($info['ghsId'] ?? 0);
  1290. if ($ghsId > 0) {
  1291. $ghsRow = GhsClass::getById($ghsId, true);
  1292. if (!empty($ghsRow)) {
  1293. $info['ghsSalt'] = $ghsRow->salt ?? '';
  1294. $ghsCustomId = intval($ghsRow->customId ?? 0);
  1295. if ($ghsCustomId > 0) {
  1296. $ghsCustom = CustomClass::getById($ghsCustomId, true);
  1297. if (!empty($ghsCustom)) {
  1298. $net = AccountMoneyClass::getNetBalanceFromRow($ghsCustom);
  1299. $info['customNetBalance'] = $net;
  1300. if (bccomp($net, '0', 2) > 0) {
  1301. $info['balance'] = floatval($net);
  1302. $info['showBalancePay'] = 1;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. $getPayType = dict::getDict('getPayType');
  1309. $info['getPayType'] = $getPayType;
  1310. //获取售后条件
  1311. $ghsId = $info['ghsId'] ?? 0;
  1312. $ghsInfo = GhsClass::getById($ghsId, true);
  1313. if (empty($ghsInfo)) {
  1314. util::fail('没有找到供货商');
  1315. }
  1316. $info['afterSale'] = $ghsInfo->afterSale ?? 1;
  1317. //重要,客户看到的电话修改成门店的联系电话
  1318. $ghsShopId = $ghsInfo->shopId ?? 0;
  1319. $ghsShopInfo = ShopClass::getById($ghsShopId, true);
  1320. $info['ghsMobile'] = $ghsShopInfo->telephone ?? '';
  1321. $info['ghsMobile2'] = $ghsShopInfo->telephone2 ?? '';
  1322. $info['hasRenew'] = 1;
  1323. //如果是快捷开单,则不需要显示累计待结,因为商家经常把快捷开单的订单发给客户结账
  1324. $showForPay = 1;
  1325. if ($ghsShopInfo->skCustomId == $info['customId']) {
  1326. $showForPay = 0;
  1327. }
  1328. $info['showForPay'] = $showForPay;
  1329. //冲销单详情页展示"原单"入口:如果当前采购单本身就是一张冲销单(forward==1),
  1330. //通过 xhCg.saleId(对应xhGhsOrder.id) 反查 xhGhsOrderForward 关联记录,
  1331. //拿到原销售单id后再取其 purchaseId 得到花店侧原采购单id,供前端跳转查看原单。ssh 冲销单功能
  1332. $forward = $info['forward'] ?? 0;
  1333. if ($forward == 1) {
  1334. $saleId = $info['saleId'] ?? 0;
  1335. if (!empty($saleId)) {
  1336. $relate = OrderForwardClass::getByForwardOrderId($saleId);
  1337. if (!empty($relate)) {
  1338. $relateOrder = OrderClass::getById($relate['orderId'], true);
  1339. if (!empty($relateOrder)) {
  1340. $info['relateCgId'] = $relateOrder->purchaseId ?? 0;
  1341. $info['relateOrderSn'] = $relate['orderSn'] ?? '';
  1342. }
  1343. }
  1344. }
  1345. }
  1346. util::success($info);
  1347. }
  1348. /**
  1349. * 按采购单查询关联的冲销记录,供 hdApp 售后记录页展示"冲销记录" ssh 冲销单功能
  1350. * xhCg.saleId 指向对应的批发销售单(xhGhsOrder.id),冲销关联记录统一存在 xhGhsOrderForward 表,
  1351. * 花店和供货商两端共用同一张表,这里直接跨命名空间复用 bizGhs\order\classes\OrderForwardClass 查询
  1352. */
  1353. public function actionGetForwardListByOrder()
  1354. {
  1355. $get = Yii::$app->request->get();
  1356. $id = $get['id'] ?? 0;
  1357. $cg = PurchaseClass::getById($id, true);
  1358. if (empty($cg)) {
  1359. util::fail('没有找到采购单');
  1360. }
  1361. if ($cg->mainId != $this->mainId) {
  1362. util::fail('无权查看');
  1363. }
  1364. $saleId = $cg->saleId ?? 0;
  1365. if (empty($saleId)) {
  1366. util::success(['list' => []]);
  1367. }
  1368. $list = OrderForwardClass::getByOrderId($saleId);
  1369. if (empty($list)) {
  1370. util::success(['list' => []]);
  1371. }
  1372. $forwardOrderIds = array_unique(array_filter(array_column($list, 'forwardOrderId')));
  1373. //冲销单在花店侧对应的采购单id(purchaseId),用于点击跳转到 hdApp 的采购单详情
  1374. $forwardOrderInfo = empty($forwardOrderIds) ? [] : OrderClass::getByIds($forwardOrderIds, null, 'id');
  1375. $data = [];
  1376. foreach ($list as $row) {
  1377. $forwardOrder = $forwardOrderInfo[$row['forwardOrderId']] ?? [];
  1378. $data[] = [
  1379. 'forwardCgId' => $forwardOrder['purchaseId'] ?? 0,
  1380. 'forwardOrderSn' => $row['forwardOrderSn'],
  1381. 'forwardPrice' => $row['forwardPrice'],
  1382. 'addTime' => $row['addTime'],
  1383. 'forwardStock' => $forwardOrder['forwardStock'] ?? 1,
  1384. ];
  1385. }
  1386. util::success(['list' => $data]);
  1387. }
  1388. //可用的支付方式 ssh 2021.1.25
  1389. public function actionPayWay()
  1390. {
  1391. $button = [
  1392. ['type' => 'wxPay', 'show' => 1, 'disable' => 1],
  1393. ['type' => 'debtPay', 'show' => 1, 'disable' => 0],
  1394. ['type' => 'balancePay', 'show' => 1, 'disable' => 0],
  1395. ];
  1396. util::success(['button' => $button]);
  1397. }
  1398. // 待结款明细:searchTime 筛开单时间 addTime,sendSearchTime 筛发货时间 sendTime
  1399. public function actionDebtList()
  1400. {
  1401. $get = Yii::$app->request->get();
  1402. $id = $get['id'] ?? 0;
  1403. $salt = $get['salt'] ?? '';
  1404. $info = GhsClass::getGhsInfo($id);
  1405. if (!empty($salt)) {
  1406. if (!isset($info['salt']) || $info['salt'] != $salt) {
  1407. util::fail('供货商出错了');
  1408. }
  1409. } else {
  1410. if (!isset($info['ownShopId']) || $info['ownShopId'] != $this->shopId) {
  1411. util::fail('错误的供货商.');
  1412. }
  1413. }
  1414. $where = ['ghsId' => $id, 'debt' => PurchaseClass::DEBT_YES];
  1415. $searchTime = $get['searchTime'] ?? '';
  1416. if (!empty($searchTime)) {
  1417. $startTime = $get['startTime'] ?? '';
  1418. $endTime = $get['endTime'] ?? '';
  1419. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  1420. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1421. }
  1422. // 发货时间筛选:按 xhCg.sendTime,可与开单时间同时生效
  1423. $sendSearchTime = $get['sendSearchTime'] ?? '';
  1424. if (!empty($sendSearchTime)) {
  1425. $sendStartTime = $get['sendStartTime'] ?? '';
  1426. $sendEndTime = $get['sendEndTime'] ?? '';
  1427. $sendPeriod = dateUtil::formatTime($sendSearchTime, $sendStartTime, $sendEndTime);
  1428. $where['sendTime'] = ['between', [$sendPeriod['startTime'], $sendPeriod['endTime']]];
  1429. }
  1430. $respond = PurchaseService::getDebtList($where);
  1431. util::success($respond);
  1432. }
  1433. //支付宝支付 ssh 2021.4.11
  1434. public function actionAliPay()
  1435. {
  1436. ini_set('date.timezone', 'Asia/Shanghai');
  1437. $post = Yii::$app->request->post();
  1438. //默认是支付宝支付
  1439. $payWay = $post['payWay'] ?? 1;
  1440. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1441. $order = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1442. if (empty($order)) {
  1443. util::fail('订单号无效');
  1444. }
  1445. if ($order->status == 5) {
  1446. util::fail('订单已取消');
  1447. }
  1448. if ($order->status != 1) {
  1449. util::fail('订单不是待付款状态');
  1450. }
  1451. $deadline = $order->deadline;
  1452. $current = time();
  1453. if (($current + 50) > strtotime($deadline)) {
  1454. util::fail('订单已失效,请重新下单');
  1455. }
  1456. $ghsId = $order->ghsId ?? 0;
  1457. $ghs = GhsClass::getById($ghsId, true);
  1458. if (empty($ghs)) {
  1459. util::fail('没有供货商信息');
  1460. }
  1461. $ghsShopId = $ghs->shopId ?? 0;
  1462. $ghsShop = ShopClass::getById($ghsShopId, true);
  1463. if (empty($ghsShop)) {
  1464. util::fail('没有供货商门店信息');
  1465. }
  1466. if (isset($ghsShop->lklSjNo) && empty($ghsShop->lklSjNo)) {
  1467. util::fail('商家支付功能未开通');
  1468. }
  1469. //避免重复提交
  1470. util::checkRepeatCommit($orderSn, 8);
  1471. //已经唤起过支付了,根据拉卡拉的规则,需要生成新的订单号
  1472. if ($order->changePrice == 2) {
  1473. $oldOrderSn = $orderSn;
  1474. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1475. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1476. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1477. $params = [
  1478. 'appid' => 'OP00002119',
  1479. 'serial_no' => '018b08cfddbd',
  1480. 'merchant_no' => $ghsShop->lklSjNo,
  1481. 'term_no' => $ghsShop->lklScanTermNo,
  1482. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1483. 'lklCertificatePath' => $lklCertificatePath,
  1484. ];
  1485. $laResource = new Lakala($params);
  1486. $closeParams = [
  1487. 'orderSn' => $oldOrderSn,
  1488. ];
  1489. $response = $laResource->cashClose($closeParams);
  1490. if (isset($response['code']) == false || $response['code'] != '000000') {
  1491. $msg = $response['msg'] ?? '';
  1492. $code = $response['code'] ?? 0;
  1493. if (!in_array($code, ['000091'])) {
  1494. noticeUtil::push('注意花店买花更换单号:' . $oldOrderSn . ',关单没有成功(收银台-支付宝),' . $msg, '15280215347');
  1495. }
  1496. }
  1497. $shopId = $order->shopId ?? 0;
  1498. $mainId = $order->mainId ?? 0;
  1499. $customId = $order->customId ?? 0;
  1500. $ghsId = $order->ghsId ?? 0;
  1501. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'customId' => $customId, 'ghsId' => $ghsId];
  1502. $newOrderSn = orderSn::getPurchaseSn($snData);
  1503. $orderSn = $newOrderSn;
  1504. $order->orderSn = $newOrderSn;
  1505. $order->save();
  1506. PurchaseItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $newOrderSn]);
  1507. }
  1508. $order->changePrice = 2;
  1509. $order->save();
  1510. $ghsShopName = $ghsShop->shopName ?? '';
  1511. //要带上哪个店的,这样才知道客户下的单是哪个店的,客户很多有多家店
  1512. $name = $ghsShopName . " 花材 " . $orderSn;
  1513. $totalFee = $order->realPrice;
  1514. $purchaseCapital = dict::getDict('capitalType', 'xhPurchase', 'id');
  1515. $ghsId = $order->ghsId ?? 0;
  1516. $ghs = GhsClass::getById($ghsId, true);
  1517. if (empty($ghs)) {
  1518. util::fail('没有供货商信息');
  1519. }
  1520. $ghsShopId = $ghs->shopId ?? 0;
  1521. $ghsShop = ShopClass::getById($ghsShopId, true);
  1522. if (empty($ghsShop)) {
  1523. util::fail('没有供货商门店信息');
  1524. }
  1525. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1526. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1527. $params = [
  1528. 'appid' => 'OP00002119',
  1529. 'serial_no' => '018b08cfddbd',
  1530. 'merchant_no' => $ghsShop->lklSjNo,
  1531. 'term_no' => $ghsShop->lklB2BTermNo,
  1532. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1533. 'lklCertificatePath' => $lklCertificatePath,
  1534. ];
  1535. $laResource = new Lakala($params);
  1536. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/cash-pay-callback";
  1537. $wxParams = [
  1538. 'orderSn' => $orderSn,
  1539. 'amount' => $totalFee,
  1540. 'capitalType' => $purchaseCapital,
  1541. 'notifyUrl' => $notifyUrl,
  1542. 'subject' => $name,
  1543. 'payWay' => $payWay,
  1544. ];
  1545. $response = $laResource->cashierPay($wxParams);
  1546. if (isset($response['code']) == false || $response['code'] != '000000') {
  1547. $errMsg = $response['msg'] ?? '';
  1548. noticeUtil::push('编号AA90:' . $errMsg, '15280215347');
  1549. util::fail('发起支付失败');
  1550. }
  1551. $counter_url = $response['resp_data']['counter_url'] ? $response['resp_data']['counter_url'] : '';
  1552. $hasRenew = $ghsShop->hasRenew ?? 0;
  1553. $new = [
  1554. 'payUrl' => $counter_url,
  1555. 'orderSn' => $orderSn,
  1556. 'hasRenew' => 1,
  1557. ];
  1558. util::success($new);
  1559. }
  1560. //微信支付 ssh 2021.4.11
  1561. public function actionWxPay()
  1562. {
  1563. ini_set('date.timezone', 'Asia/Shanghai');
  1564. $post = Yii::$app->request->post();
  1565. $couponId = $post['couponId'] ?? 0;
  1566. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1567. $order = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1568. if (empty($order)) {
  1569. util::fail('订单号无效');
  1570. }
  1571. if ($order->status == 5) {
  1572. util::fail('订单已取消');
  1573. }
  1574. if ($order->status != 1) {
  1575. util::fail('订单不是待付款状态');
  1576. }
  1577. $deadline = $order->deadline;
  1578. $current = time();
  1579. if (($current + 50) > strtotime($deadline)) {
  1580. util::fail('订单已失效,请重新下单');
  1581. }
  1582. //避免重复提交
  1583. util::checkRepeatCommit($orderSn, 8);
  1584. $ghsId = $order->ghsId ?? 0;
  1585. $ghs = GhsClass::getById($ghsId, true);
  1586. if (empty($ghs)) {
  1587. util::fail('没有供货商信息');
  1588. }
  1589. $ghsShopId = $ghs->shopId ?? 0;
  1590. $ghsShop = ShopClass::getById($ghsShopId, true);
  1591. if (empty($ghsShop)) {
  1592. util::fail('没有供货商门店信息');
  1593. }
  1594. if (isset($ghsShop->lklSjNo) && empty($ghsShop->lklSjNo)) {
  1595. util::fail('商家支付功能未开通');
  1596. }
  1597. //已经唤起过微信支付了,根据拉卡拉的规则,需要生成新的订单号
  1598. if ($order->changePrice == 2) {
  1599. $oldOrderSn = $orderSn;
  1600. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1601. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1602. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1603. $params = [
  1604. 'appid' => 'OP00002119',
  1605. 'serial_no' => '018b08cfddbd',
  1606. 'merchant_no' => $ghsShop->lklSjNo,
  1607. 'term_no' => $ghsShop->lklScanTermNo,
  1608. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1609. 'lklCertificatePath' => $lklCertificatePath,
  1610. ];
  1611. $laResource = new Lakala($params);
  1612. $closeParams = [
  1613. 'orderSn' => $oldOrderSn,
  1614. ];
  1615. $response = $laResource->close($closeParams);
  1616. if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
  1617. $msg = $response['msg'] ?? '';
  1618. $code = $response['code'] ?? 0;
  1619. if (!in_array($code, ['BBS11114'])) {
  1620. noticeUtil::push('重点注意,花店买花更换单号没有成功,单号:' . $oldOrderSn . ',关单没有成功,' . $msg . $code, '15280215347');
  1621. util::fail('出错了,请重新下单');
  1622. }
  1623. }
  1624. $shopId = $order->shopId ?? 0;
  1625. $mainId = $order->mainId ?? 0;
  1626. $customId = $order->customId ?? 0;
  1627. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'customId' => $customId, 'ghsId' => $ghsId];
  1628. $newOrderSn = orderSn::getPurchaseSn($snData);
  1629. $orderSn = $newOrderSn;
  1630. $order->orderSn = $newOrderSn;
  1631. $order->save();
  1632. PurchaseItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $newOrderSn]);
  1633. }
  1634. $id = $order->id;
  1635. $order->changePrice = 2;
  1636. $order->save();
  1637. $ghsShopName = $ghsShop->shopName ?? '';
  1638. //要带上哪个店的,这样才知道客户下的单是哪个店的,客户很多有多家店
  1639. $name = $ghsShopName . " 花材 " . $orderSn;
  1640. $totalFee = $order->realPrice;
  1641. $openId = '';
  1642. if (isset($post['currentMiniOpenId']) && !empty($post['currentMiniOpenId'])) {
  1643. $openId = $post['currentMiniOpenId'];
  1644. //noticeUtil::push('花店采购下单时,通过前端获取了openId:' . $openId, '15280215347');
  1645. }
  1646. if (empty($openId)) {
  1647. if (isset($this->admin) && !empty($this->admin)) {
  1648. if (isset($this->admin->miniOpenId) && !empty($this->admin->miniOpenId)) {
  1649. $openId = $this->admin->miniOpenId;
  1650. noticeUtil::push('花店采购下单时,通过数据库获取了openId:' . $openId, '15280215347');
  1651. }
  1652. }
  1653. }
  1654. if (empty($openId)) {
  1655. $currentShopId = $order->shopId ?? 0;
  1656. $currentShop = ShopClass::getById($currentShopId, true);
  1657. $currentShopName = $currentShop->merchantName . ' ' . $currentShop->shopName;
  1658. $currentMobile = $currentShop->mobile ?? '';
  1659. noticeUtil::push("花店采购时,发现没有openId,请跟进是否采购成功。{$currentShopName} {$currentMobile}", '15280215347');
  1660. util::success(['hasError' => 1, 'hasNoMiniOpenId' => 1]);
  1661. }
  1662. $purchaseCapital = dict::getDict('capitalType', 'xhPurchase', 'id');
  1663. //花卉宝代为申请的微信支付
  1664. $merchantExtend = WxOpenClass::getWxInfo();
  1665. if (empty($ghsShop->lklSjNo)) {
  1666. noticeUtil::push('编号31505:单号:' . $orderSn . ' 商家没有开通收款功能:' . $ghsShopName, '15280215347');
  1667. util::fail('商家未开通支付功能');
  1668. }
  1669. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1670. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1671. $params = [
  1672. 'appid' => 'OP00002119',
  1673. 'serial_no' => '018b08cfddbd',
  1674. 'merchant_no' => $ghsShop->lklSjNo,
  1675. 'term_no' => $ghsShop->lklScanTermNo,
  1676. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1677. 'lklCertificatePath' => $lklCertificatePath,
  1678. ];
  1679. $laResource = new Lakala($params);
  1680. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  1681. $wxParams = [
  1682. 'orderSn' => $orderSn,
  1683. 'amount' => $totalFee,
  1684. 'capitalType' => $purchaseCapital,
  1685. 'notifyUrl' => $notifyUrl,
  1686. 'wxAppId' => $merchantExtend['miniAppId'],
  1687. 'openId' => $openId,
  1688. 'subject' => $name,
  1689. 'couponId' => $couponId,
  1690. ];
  1691. $response = $laResource->driveWxPay($wxParams);
  1692. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1693. $errMsg = $response['msg'] ?? '';
  1694. noticeUtil::push('编号129680931:' . $errMsg . ' 单号:' . $orderSn . ' ' . $ghsShopName, '15280215347');
  1695. util::fail('支付失败');
  1696. }
  1697. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  1698. $appId = $newParams['app_id'] ?? '';
  1699. $nonceStr = $newParams['nonce_str'] ?? '';
  1700. $paySign = $newParams['pay_sign'] ?? '';
  1701. $package = $newParams['package'] ?? '';
  1702. $signType = $newParams['sign_type'] ?? '';
  1703. $timeStamp = $newParams['time_stamp'] ?? '';
  1704. $new = [
  1705. 'id' => $id,
  1706. 'appId' => $appId,
  1707. 'nonceStr' => $nonceStr,
  1708. 'paySign' => $paySign,
  1709. 'package' => $package,
  1710. 'signType' => $signType,
  1711. 'timeStamp' => $timeStamp,
  1712. 'orderSn' => $orderSn,
  1713. ];
  1714. util::success($new);
  1715. }
  1716. //计算运费 ssh 20221003
  1717. public function actionFreight()
  1718. {
  1719. $get = Yii::$app->request->get();
  1720. $shop = $this->shop;
  1721. $ghsId = $get['ghsId'] ?? 0;
  1722. $ghs = GhsClass::getById($ghsId, true);
  1723. if (empty($ghs)) {
  1724. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1725. }
  1726. $ghsShopId = $ghs->shopId ?? 0;
  1727. $ghsShop = ShopClass::getById($ghsShopId, true);
  1728. if (empty($ghsShop)) {
  1729. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1730. }
  1731. $customId = $ghs->customId ?? 0;
  1732. $custom = CustomClass::getById($customId, true);
  1733. if (empty($custom)) {
  1734. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1735. }
  1736. $weight = $get['weight'] ?? 0;
  1737. if (empty($weight)) {
  1738. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1739. }
  1740. $respond = PurchaseClass::getDistanceFee($shop, $ghsShop, $weight, $custom);
  1741. util::success($respond);
  1742. }
  1743. //运费计算 lqh 2021.4.12 暂时返回固定值
  1744. public function actionFreight2()
  1745. {
  1746. //lqh 2021.6.25 运费固定返回0
  1747. util::success(['sedCost' => 0]);
  1748. }
  1749. }