PurchaseController.php 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  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. util::fail('算运费失败,请更换配送方式');
  600. }
  601. //计算客户到店的距离,骑电动车
  602. $distanceRespond = mapUtil::calcShopDistanceByEleBike($custom, $ghsShopInfo);
  603. $sendDistance = $distanceRespond['distanceKm'] ?? 0;
  604. if ($sendDistance <= 0) {
  605. util::fail('算运费失败,距离是0,请选到店自取');
  606. }
  607. // 计算运费逻辑
  608. $sendCost = $startPrice;
  609. if ($sendDistance > $startKm) {
  610. $extraDistance = bcsub($sendDistance, $startKm, 2);
  611. $extraCost = bcmul($extraDistance, $perKmPrice, 2);
  612. $sendCost = bcadd($sendCost, $extraCost, 2);
  613. }
  614. if ($changeRate != 0) {
  615. // 临时涨价/降价百分比
  616. $rate = bcadd(1, bcdiv($changeRate, 100, 4), 4);
  617. $sendCost = bcmul($sendCost, $rate, 2);
  618. }
  619. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $sendCost, 2);
  620. $post['sendDistance'] = $sendDistance;
  621. } else {
  622. // 使用 DeliveryQuoteUtil 获取配送报价
  623. try {
  624. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  625. 'productList' => $productList,
  626. 'deliveryPlatform' => $post['deliveryPlatform'],
  627. 'deliveryBracketContent' => $post['deliveryBracketContent'], // 平台多报价识别id
  628. 'ghsInfo' => $ghsInfo,
  629. 'custom' => $custom,
  630. 'order' => [
  631. 'orderSn' => $orderSn,
  632. 'goodsType' => 1, //商品类型:0 花束 1 花材
  633. 'itemTotalAmount' => $post['itemTotalAmount'] ?? 0,
  634. 'remark' => $post['remark'] ?? '',
  635. ],
  636. 'mainId' => $this->mainId,
  637. 'productCount' => $productCount,
  638. //当前配送方式
  639. 'shConfig' => $shCurrentConfig,
  640. ]);
  641. $sendCost = $quoteResult['sendCost'];
  642. $sendDistance = $quoteResult['sendDistance'];
  643. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $sendCost, 2);
  644. $post['sendDistance'] = $sendDistance;
  645. } catch (\Exception $e) {
  646. noticeUtil::push("计算跑腿费用出错了:" . $e->getMessage(), '15280215347');
  647. util::fail('下单失败,请选其他配送方式');
  648. }
  649. }
  650. } else {
  651. //如果是不是发跑腿,比如送货上门和发快递,则可能要收运费或打包费任一
  652. $shMethodBigNum = 0;
  653. foreach ($productList as $itemData) {
  654. $shMethodBigNum += floatval($itemData['bigNum'] ?? 0);
  655. }
  656. $additionalCosts = ShMethodClass::calcFee(
  657. $shCurrentConfig,
  658. $sendType,
  659. $shMethodItemAmount,
  660. $shMethodBigNum,
  661. $customId,
  662. $ghsInfo
  663. );
  664. // 如果产生了附加运费,与前面可能产生的 sendCost 进行累加或覆盖
  665. if ($additionalCosts['sendCost'] > 0) {
  666. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $additionalCosts['sendCost'], 2);
  667. }
  668. // 如果产生了附加包装费,覆盖前面赋值的 packCost。
  669. if ($additionalCosts['packCost'] > 0) {
  670. $post['packCost'] = $additionalCosts['packCost'];
  671. }
  672. }
  673. } else {
  674. //同城发货包装费和运费的计算
  675. $sendCost = 0;
  676. $sendDistance = 0;
  677. //特别注意,这边取供货商的shop信息
  678. $mapSet = ShopClass::hasIntraCity($ghsShopInfo);
  679. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  680. if ($sendType == dict::getDict('sendType', 'thirdSend')) {
  681. if ($openIntraCity == 2) {
  682. util::fail('不能使用跑腿');
  683. }
  684. if ($openIntraCity == 1) {
  685. // 生成随机订单号,不要跟原来的单号混起来,跑腿-销售单-
  686. $prefix = 'PT-XSD-' . $this->mainId . '-';
  687. $orderSn = $prefix . round(microtime(true) * 1000);
  688. // 使用 DeliveryQuoteUtil 获取配送报价
  689. try {
  690. if (empty($post['deliveryPlatform'])) {
  691. util::fail('请选择跑腿');
  692. }
  693. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  694. 'productList' => $productList,
  695. 'deliveryPlatform' => $post['deliveryPlatform'],
  696. 'deliveryBracketContent' => $post['deliveryBracketContent'], // 平台多报价识别id
  697. 'ghsInfo' => $ghsInfo,
  698. 'custom' => $custom,
  699. 'order' => [
  700. 'orderSn' => $orderSn,
  701. 'goodsType' => 1, //商品类型:0花束 1花材
  702. 'itemTotalAmount' => $post['itemTotalAmount'] ?? 0,
  703. 'remark' => $post['remark'] ?? '',
  704. ],
  705. 'mainId' => $this->mainId,
  706. 'productCount' => $productCount,
  707. ]);
  708. $sendCost = $quoteResult['sendCost'];
  709. $sendDistance = $quoteResult['sendDistance'];
  710. } catch (\Exception $e) {
  711. noticeUtil::push("计算跑腿费用出错了:" . $e->getMessage(), '15280215347');
  712. util::fail('下单失败,请选其他配送方式');
  713. }
  714. }
  715. }
  716. $post['sendCost'] = $sendCost;
  717. $post['sendDistance'] = $sendDistance;
  718. // 出车(0)、发快递(4)、发物流可以算包装费
  719. $packCost = 0;
  720. if (isset($ghsInfo['mainId']) && $ghsInfo['mainId'] == 14499) {
  721. noticeUtil::push("走的pfLevel=0", '15280215347');
  722. }
  723. $itemTotalAmount = $post['itemTotalAmount'] ?? 0;
  724. unset($post['itemTotalAmount']);
  725. // sendType == 4 要收包装费
  726. if ($sendType == 4) {
  727. $needAdd = \bizHd\shop\classes\ShopClass::needAddPackCost($ghsShopInfo, $customId, $sendType, $itemTotalAmount);
  728. if ($needAdd) {
  729. $packCost = $ghsShopInfo->packCost ?? 0;
  730. }
  731. }
  732. $post['packCost'] = $packCost;
  733. }
  734. }
  735. $respond = PurchaseService::createPurchase($post, $ghsInfo);
  736. $newStatus = dict::getNewMethod($ghsShopId);
  737. if ($newStatus) {
  738. // 使用 xhShMethod 配置校验配送限制,替代旧版门店硬编码规则,关键词 sh_method_area
  739. $shMethodError = ShMethodClass::checkLimit(
  740. $ghsShopId,
  741. $ghsMainId,
  742. $sendType,
  743. $respond->actPrice ?? 0,
  744. $respond->bigNum ?? 0,
  745. $post['packCost'] ?? 0,
  746. $post['sendCost'] ?? 0,
  747. $post['wlName'] ?? '',
  748. $customId,
  749. $ghsInfo
  750. );
  751. if ($shMethodError !== '') {
  752. $transaction->rollBack();
  753. util::fail($shMethodError);
  754. }
  755. } else {
  756. if ($sendType == 0) {
  757. if (getenv('YII_ENV') == 'production') {
  758. //杭州斗南鲜花批发部,满500,10公里内免费配送,满1000,20公里免费配送
  759. if ($ghsShopId == 4608) {
  760. if ($respond->actPrice < 500) {
  761. $transaction->rollBack();
  762. util::fail('满500元支持免费配送');
  763. }
  764. }
  765. //叶上花,满500元市区免费配送
  766. if ($ghsShopId == 4804) {
  767. if ($respond->actPrice < 500) {
  768. $transaction->rollBack();
  769. util::fail('满500元支持免费配送');
  770. }
  771. }
  772. //花悠星 国恋 勇记 万丽 陆丰暂时不支持免费配送
  773. if ($ghsShopId == 7687 || $ghsShopId == 7831 || $ghsShopId == 7778 || $ghsShopId == 12003 || $ghsShopId == 38128) {
  774. util::fail('暂不支持送货上门,请选其它配送方式!');
  775. }
  776. //广州鑫源花卉,选择送货上门必须选必选商品
  777. if ($ghsShopId == 12439) {
  778. $hasMust = array_intersect($ids, [3446945, 3446970, 3446973, 3446979, 3446995, 3447010, 3447023, 3459983, 4333184, 4317745, 1585738]);
  779. if (empty($hasMust)) {
  780. util::fail('请返回选择 必选商品');
  781. }
  782. }
  783. //情意花卉,必选品
  784. if ($ghsShopId == 100883) {
  785. $hasMust = array_intersect($ids, [5017957, 5036067, 5036089, 5036099, 5017958, 5036063, 5017948, 5035980, 5036073, 5036075, 5036076, 5036117, 5036118, 5017949, 5035979, 5035976, 5035928, 5035930, 5036061, 5035879]);
  786. if (empty($hasMust)) {
  787. util::fail('请返回选择 必选商品');
  788. }
  789. }
  790. //三明易批花
  791. if ($ghsShopId == 82200) {
  792. if ($respond->actPrice < 100 || $respond->bigNum < 15) {
  793. $hasMust = array_intersect($ids, [4283478]);
  794. if (empty($hasMust)) {
  795. util::fail('没满100元且15扎,请返回选运费');
  796. }
  797. }
  798. // 按当天计时,把 sendTimeWant 要限制在两天的时间范围之内
  799. $future = date("Y-m-d", strtotime('+2 day'));
  800. if (strtotime($respond->sendTimeWant) > strtotime($future)) {
  801. util::fail('配送日期只能选最近二天');
  802. }
  803. }
  804. if ($ghsShopId == 77703) {
  805. //天天鲜花思明店,暂时关闭送货上门
  806. if ($respond->sendType == 0) {
  807. //util::fail('节日暂停送货上门,请选到店自取');
  808. }
  809. }
  810. if ($ghsShopId == 86726) {
  811. //藏花林
  812. if ($respond->transType != 4 && $respond->transType != 5) {
  813. util::fail('请选同城配送或到店自取');
  814. }
  815. }
  816. }
  817. if (isset($ghsInfo['home'])) {
  818. if ($ghsInfo['home'] == 0) {
  819. util::fail('暂不支持送货上门,请选其它配送方式');
  820. }
  821. $homeAmount = $ghsInfo['homeAmount'] ? floatval($ghsInfo['homeAmount']) : 0;
  822. $homeNum = $ghsInfo['homeNum'] ? floatval($ghsInfo['homeNum']) : 0;
  823. if ($homeAmount > 0 && $homeAmount > $respond->actPrice) {
  824. util::fail("满{$homeAmount}元 可送货上门");
  825. }
  826. if ($homeNum > 0 && $homeNum > $respond->bigNum) {
  827. util::fail("满{$homeNum}扎 可送货上门");
  828. }
  829. }
  830. }
  831. if ($sendType == 2) {
  832. //温州易批花,跑腿,不满100,要选10元的补运费商品
  833. if ($ghsShopId == 91115) {
  834. if ($respond->actPrice < 100) {
  835. $transaction->rollBack();
  836. $hasMust = array_intersect($ids, [4449812, 4449811]);
  837. if (empty($hasMust)) {
  838. util::fail('不满100,必选商品 补运费10元');
  839. }
  840. }
  841. }
  842. }
  843. if ($sendType == 4) {
  844. //温州易批花,快递,不满100,要选10元的补运费商品
  845. if ($ghsShopId == 91115) {
  846. if ($respond->actPrice < 100) {
  847. $transaction->rollBack();
  848. $hasMust = array_intersect($ids, [4449812, 4449811]);
  849. if (empty($hasMust)) {
  850. util::fail('不满100,必选商品 补运费10元');
  851. }
  852. }
  853. }
  854. }
  855. if ($sendType == 3) {
  856. //温州易批花,物流,不满200,要选10元的补运费商品
  857. if ($ghsShopId == 91115) {
  858. if ($respond->actPrice < 200) {
  859. $transaction->rollBack();
  860. $hasMust = array_intersect($ids, [4449812, 4449811]);
  861. if (empty($hasMust)) {
  862. util::fail('不满200,必选商品 补运费10元');
  863. }
  864. }
  865. }
  866. }
  867. }
  868. $transaction->commit();
  869. $transactionFinished = true;
  870. ProductClass::clearLimitBuyRollbackSnapshot();
  871. util::success($respond);
  872. } catch (\Exception $e) {
  873. if ($transaction->isActive) {
  874. $transaction->rollBack();
  875. }
  876. ProductClass::rollbackLimitBuySnapshot();
  877. $transactionFinished = true;
  878. Yii::error($e->getMessage());
  879. util::fail();
  880. }
  881. }
  882. /**
  883. * 赊账支付
  884. * 职责:处理采购单延期支付(记欠款/赊账),更新采购单状态,并触发后续的自动收货、通知、在线打印、跑腿呼叫等业务流
  885. * 入参:GET 传参 orderSn (采购单号)
  886. * 返回:JSON 格式的采购单属性
  887. * 副作用:更新采购单、订单状态,增减花材库存并记录库存流水,更新客户及供货商的最后下单时间,发送外部通知和打印请求
  888. * 关键边界:
  889. * 1. 校验采购单及客户的赊账权限
  890. * 2. 优化:复用采购单实例,避免重复查询
  891. * 3. 优化:将自动确认收货(confirmTake)包裹在独立事务中,合并写操作,减少磁盘 I/O
  892. * 4. 优化:合并打印逻辑中的 ShopExt 查询及订单保存,减少数据库交互
  893. * 5. 优化:使用 updateByCondition 直接更新最后下单时间,避免先 SELECT 再 UPDATE
  894. */
  895. public function actionDebtPay()
  896. {
  897. $get = Yii::$app->request->get();
  898. $orderSn = $get['orderSn'] ?? 0;
  899. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  900. PurchaseService::valid($info, $this->shopId);
  901. //解决重复和并发提交
  902. $cacheKey = 'hd_debt_pay_' . $orderSn;
  903. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  904. if (!empty($has)) {
  905. util::fail('请稍等...');
  906. }
  907. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 5, 'has']);
  908. if ($info->status == 5) {
  909. util::fail('订单已取消');
  910. }
  911. if ($info->status != 1) {
  912. util::fail('订单不是待付款状态');
  913. }
  914. if ($info->book == 1) {
  915. util::fail('预售不能记欠款');
  916. }
  917. $ghsId = $info->ghsId;
  918. $ghs = GhsClass::getGhsInfo($ghsId);
  919. $customId = $ghs['customId'] ?? 0;
  920. $custom = CustomClass::getCustom($customId);
  921. if (empty($custom)) {
  922. util::fail('没有找到客户');
  923. }
  924. if (isset($custom['debt']) == false || $custom['debt'] == CustomClass::IS_DEBT_NO) {
  925. util::fail('请先申请赊账权限');
  926. }
  927. if (getenv('YII_ENV') == 'production') {
  928. //源花汇不允许客户自己下欠款单
  929. if ($ghs['mainId'] == 10536) {
  930. util::fail('暂未开通');
  931. }
  932. }
  933. $connection = Yii::$app->db;
  934. $transaction = $connection->beginTransaction();
  935. try {
  936. //延期支付
  937. PurchaseService::debt($info);
  938. $transaction->commit();
  939. if (isset($info->localOrder) && $info->localOrder == 1) {
  940. if ($info->transType != 5 && $info->transType != 4) {
  941. //昆明发货,客户算了一次打包费和运费,第二次就不再算了
  942. $current = date("Y_m_d");
  943. $key = 'ghs_custom_today_has_get_pack_cost_' . $current . '_' . $customId;
  944. Yii::$app->redis->executeCommand('SETEX', [$key, 86400, '1']);
  945. }
  946. } else {
  947. //标记当配送方式已收一次包装费/运费,只要有成功单就标记,后续不再重复要求门槛或加收费用
  948. $current = date("Y_m_d");
  949. if (isset($info->sendType)) {
  950. $key = 'ghs_custom_today_has_get_pack_cost_' . $info->sendType . '_' . $current . '_' . $customId;
  951. Yii::$app->redis->executeCommand('SETEX', [$key, 86400, '1']);
  952. // 兼容快递/送货/跑腿收运费或限制下单的情况
  953. $sendKey = 'ghs_custom_today_has_get_send_cost_' . $info->sendType . '_' . $current . '_' . $customId;
  954. Yii::$app->redis->executeCommand('SETEX', [$sendKey, 86400, '1']);
  955. }
  956. }
  957. // 复杂分支/关键逻辑:不是预订单,且供货商配置为直接完成流程,则自动确认收货。
  958. // 优化:复用已有的 $info 实例,避免重复查询;同时将自动确认收货包裹在独立事务中,合并批量写操作,减少磁盘 I/O。
  959. if (!empty($info)) {
  960. if (isset($info->book) && $info->book == 0) {
  961. $ghsShopId = $ghs['shopId'] ?? 0;
  962. $ext = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,orderFlow');
  963. if (!empty($ext) && intval($ext->orderFlow ?? 0) === 0) {
  964. $takeTransaction = Yii::$app->db->beginTransaction();
  965. try {
  966. PurchaseClass::confirmTake($info);
  967. $takeTransaction->commit();
  968. } catch (\Exception $takeEx) {
  969. $takeTransaction->rollBack();
  970. Yii::error("自动确认收货失败: " . $takeEx->getMessage());
  971. throw $takeEx;
  972. }
  973. }
  974. }
  975. }
  976. //app新订单通知
  977. $saleId = $info->saleId ?? 0;
  978. $order = OrderClass::getById($saleId, true);
  979. if (!empty($order)) {
  980. $shopId = $order->shopId ?? 0;
  981. $shop = ShopClass::getById($shopId, true);
  982. if (!empty($shop)) {
  983. //通知供货商
  984. GhsNotifyClass::newOrderNotify($saleId);
  985. }
  986. //订单生成时唤起在线打印
  987. if (isset($order->needPrint) && $order->needPrint == dict::getDict('needPrint', 'need')) {
  988. //有几个地方要同步去修改
  989. if (getenv('YII_ENV') == 'production') {
  990. //源花汇、盛丰不自动打小票,关键词mall_order_no_auto_print
  991. $mallOrderNoPrint = [10536, 44282, 26374];
  992. } else {
  993. $mallOrderNoPrint = [];
  994. }
  995. if (!in_array($order->mainId, $mallOrderNoPrint)) {
  996. // 复杂分支/关键逻辑:优化:只查询一次 $ext,合并 $order->save(),减少数据库交互
  997. $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  998. $hasPrintSn = isset($ext->printSn) && !empty($ext->printSn);
  999. OrderClass::onlinePrint($order);
  1000. if ($hasPrintSn) {
  1001. $order->printNum += 1;
  1002. }
  1003. //花镜 打二次小票,有多处要修改搜索关键词tow_print
  1004. if (in_array($order->mainId, [76796])) {
  1005. OrderClass::onlinePrint($order);
  1006. if ($hasPrintSn) {
  1007. $order->printNum += 1;
  1008. }
  1009. }
  1010. if ($hasPrintSn) {
  1011. $order->save();
  1012. }
  1013. }
  1014. }
  1015. //付款成功之后呼叫跑腿,关键词 pay_after_call_pt,多处要同步修改
  1016. GhsDeliveryOrderClass::payAfter($order);
  1017. // 复杂分支/关键逻辑:优化:使用 updateByCondition 直接更新最后下单时间,避免先 SELECT 再 UPDATE 的性能开销
  1018. $customId = $order->customId ?? 0;
  1019. $ghsId = $order->ghsId ?? 0;
  1020. $date = date("Y-m-d H:i:s");
  1021. if ($customId > 0) {
  1022. CustomClass::updateByCondition(['id' => $customId], ['recentExpend' => $date]);
  1023. }
  1024. if ($ghsId > 0) {
  1025. GhsClass::updateByCondition(['id' => $ghsId], ['recentExpend' => $date]);
  1026. }
  1027. }
  1028. } catch (\Exception $e) {
  1029. $transaction->rollBack();
  1030. Yii::error("赊账支付失败原因:" . $e->getMessage());
  1031. util::fail('支付失败');
  1032. }
  1033. util::success($info->attributes);
  1034. }
  1035. /**
  1036. * 采购待支付页:客户 xhGhsCustom 净余额支付(并发重试 + 行锁)。
  1037. */
  1038. public function actionCustomBalancePay()
  1039. {
  1040. $post = Yii::$app->request->post();
  1041. $orderSn = $post['orderSn'] ?? '';
  1042. if (empty($orderSn)) {
  1043. util::fail('订单号无效');
  1044. }
  1045. $cacheKey = 'hd_custom_balance_pay_' . $orderSn;
  1046. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1047. if (!empty($has)) {
  1048. util::fail('请稍等...');
  1049. }
  1050. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 8, 'has']);
  1051. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1052. if (empty($info)) {
  1053. util::fail('没有找到采购单');
  1054. }
  1055. PurchaseService::valid($info, $this->shopId);
  1056. $deadline = $info->deadline ?? '';
  1057. if (!empty($deadline) && time() > strtotime($deadline)) {
  1058. util::fail('订单已失效了哦');
  1059. }
  1060. $ghsId = intval($info->ghsId ?? 0);
  1061. $ghs = GhsClass::getGhsInfo($ghsId);
  1062. try {
  1063. $result = util::runWithDbConcurrencyRetry(function () use ($orderSn) {
  1064. $connection = Yii::$app->db;
  1065. $transaction = $connection->beginTransaction();
  1066. try {
  1067. $purchase = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1068. $respond = PurchaseService::payByGhsCustomBalance($purchase);
  1069. $transaction->commit();
  1070. return $respond;
  1071. } catch (\Exception $exception) {
  1072. if ($transaction->isActive) {
  1073. $transaction->rollBack();
  1074. }
  1075. throw $exception;
  1076. }
  1077. });
  1078. $info = $result['purchase'];
  1079. $order = $result['saleOrder'] ?? null;
  1080. if (!empty($order)) {
  1081. if (isset($info->book) && $info->book == 0 && !empty($ghs)) {
  1082. $ghsShopId = $ghs['shopId'] ?? 0;
  1083. $ext = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,orderFlow');
  1084. if (!empty($ext) && intval($ext->orderFlow ?? 0) === 0) {
  1085. $cg = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1086. if (!empty($cg)) {
  1087. PurchaseClass::confirmTake($cg);
  1088. }
  1089. }
  1090. }
  1091. $shopId = $order->shopId ?? 0;
  1092. $shop = ShopClass::getById($shopId, true);
  1093. if (!empty($shop)) {
  1094. GhsNotifyClass::newOrderNotify($order->id ?? 0);
  1095. }
  1096. if (isset($order->needPrint) && $order->needPrint == dict::getDict('needPrint', 'need')) {
  1097. OrderClass::onlinePrint($order);
  1098. }
  1099. GhsDeliveryOrderClass::payAfter($order);
  1100. $customId = $order->customId ?? 0;
  1101. $custom = CustomClass::getById($customId, true);
  1102. $date = date('Y-m-d H:i:s');
  1103. if (!empty($custom)) {
  1104. $custom->recentExpend = $date;
  1105. $custom->save();
  1106. }
  1107. $orderGhsId = $order->ghsId ?? 0;
  1108. $orderGhs = GhsClass::getById($orderGhsId, true);
  1109. if (!empty($orderGhs)) {
  1110. $orderGhs->recentExpend = $date;
  1111. $orderGhs->save();
  1112. }
  1113. }
  1114. util::success($info->attributes);
  1115. } catch (\Exception $e) {
  1116. Yii::info('客户余额支付失败:' . $e->getMessage());
  1117. util::fail($e->getMessage() ?: '支付失败');
  1118. }
  1119. }
  1120. //余额支付 ssh 2021.1.24
  1121. public function actionBalancePay()
  1122. {
  1123. $shopAdmin = $this->shopAdmin;
  1124. if (isset($shopAdmin->super) == false || $shopAdmin->super != 1) {
  1125. util::fail('超管才能操作');
  1126. }
  1127. $get = Yii::$app->request->get();
  1128. $orderSn = $get['orderSn'] ?? 0;
  1129. $password = $get['password'] ?? '';
  1130. // 重新获取,不加密的用户数据
  1131. $admin = AdminClass::getById($this->adminId, true);
  1132. if (password_verify($password, $admin->payPassword) == false) {
  1133. util::fail('密码错误');
  1134. }
  1135. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1136. if (empty($info)) {
  1137. util::fail('没有找到采购单');
  1138. }
  1139. if ($info->status == 5) {
  1140. util::fail('订单已取消');
  1141. }
  1142. if ($info->status != 1) {
  1143. util::fail('订单不是待付款状态');
  1144. }
  1145. PurchaseService::valid($info, $this->shopId);
  1146. $connection = Yii::$app->db;
  1147. $transaction = $connection->beginTransaction();
  1148. try {
  1149. //余额支付
  1150. purchaseService::balancePay($info);
  1151. $transaction->commit();
  1152. } catch (\Exception $e) {
  1153. $transaction->rollBack();
  1154. util::fail('支付失败');
  1155. }
  1156. util::success($info->attributes);
  1157. }
  1158. //采购记录 ssh 2021.1.24
  1159. public function actionList()
  1160. {
  1161. $get = Yii::$app->request->get();
  1162. $where = ['shopId' => $this->shopId];
  1163. $searchTime = $get['searchTime'] ?? '';
  1164. if (!empty($searchTime)) {
  1165. $startTime = $get['startTime'] ?? '';
  1166. $endTime = $get['endTime'] ?? '';
  1167. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  1168. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1169. }
  1170. $ghsId = $get['ghsId'] ?? 0;
  1171. if (!empty($ghsId)) {
  1172. $where['ghsId'] = (int)$ghsId;
  1173. }
  1174. $status = $get['status'] ?? 0;
  1175. if (!empty($status)) {
  1176. $where['status'] = $status;
  1177. }
  1178. $respond = PurchaseService::getPurchaseList($where);
  1179. $respond['shop'] = $this->shop->attributes;
  1180. util::success($respond);
  1181. }
  1182. //获取合并采购单列表 ssh 20260519
  1183. public function actionMergeOrderList()
  1184. {
  1185. Yii::$app->params['pageSize'] = 9999;
  1186. $get = Yii::$app->request->get();
  1187. $mergeId = $get['mergeId'] ?? 0;
  1188. if (empty($mergeId)) {
  1189. util::fail('请选择采购单');
  1190. }
  1191. $mergeSn = CgMergeSnClass::getById($mergeId, true);
  1192. if (empty($mergeSn)) {
  1193. util::fail('请选择合并采购单');
  1194. }
  1195. $salt = $get['salt'] ?? '';
  1196. if (!empty($salt)) {
  1197. if (empty($mergeSn->salt) || $mergeSn->salt != $salt) {
  1198. util::fail('此单无法查看哦');
  1199. }
  1200. } else {
  1201. if (empty($this->shopId)) {
  1202. util::fail('暂时不能查看');
  1203. }
  1204. if ($mergeSn->mainId != $this->mainId) {
  1205. util::fail('此单无法查看哈');
  1206. }
  1207. }
  1208. $ghsId = $mergeSn->ghsId ?? 0;
  1209. $where = [
  1210. 'ghsId' => $ghsId,
  1211. 'mergeId' => $mergeId,
  1212. ];
  1213. $respond = PurchaseService::getPurchaseList($where);
  1214. $totalPrice = 0;
  1215. if (!empty($respond['list'])) {
  1216. foreach ($respond['list'] as $one) {
  1217. $actPrice = $one['actPrice'] ?? 0;
  1218. $totalPrice = bcadd($totalPrice, $actPrice, 2);
  1219. }
  1220. }
  1221. $totalPrice = floatval($totalPrice);
  1222. $respond['totalPrice'] = $totalPrice;
  1223. $respond['shop'] = !empty($this->shop) ? $this->shop->attributes : [];
  1224. util::success($respond);
  1225. }
  1226. //采购详情 ssh 2021.01.25
  1227. public function actionDetail()
  1228. {
  1229. $get = Yii::$app->request->get();
  1230. $id = $get['id'] ?? 0;
  1231. $info = PurchaseService::getInfo($id, true, true);
  1232. if (empty($info)) {
  1233. util::fail('没有找到采购单');
  1234. }
  1235. $salt = $get['salt'] ?? '';
  1236. if (!empty($salt)) {
  1237. if (!isset($info['salt']) || $info['salt'] != $salt) {
  1238. util::fail('无效采购单呢!');
  1239. }
  1240. } else {
  1241. if (!isset($info['mainId']) || $info['mainId'] != $this->mainId) {
  1242. //util::fail('采购单不能访问');
  1243. }
  1244. }
  1245. $customId = $info['customId'] ?? 0;
  1246. $custom = CustomClass::getById($customId);
  1247. $customName = $custom['name'] ?? '';
  1248. $customMobile = $custom['mobile'] ?? '';
  1249. $info['customName'] = $customName;
  1250. $info['customMobile'] = $customMobile;
  1251. $hasDebtPay = $custom['debt'] ?? 0;
  1252. $book = $info['book'] ?? 0;
  1253. $presell = $info['presell'] ?? 0;
  1254. //预售不能记欠款
  1255. if ($book == 1) {
  1256. $hasDebtPay = 0;
  1257. }
  1258. if ($presell == 1) {
  1259. $hasDebtPay = 0;
  1260. }
  1261. $shop = $this->shop;
  1262. $info['pfShopId'] = $shop->pfShopId ?? 0;
  1263. $info['hasDebtPay'] = $hasDebtPay;
  1264. // 待支付页展示 xhGhsCustom 净余额(正数=可支付余额),不再使用 main.balance
  1265. $info['balance'] = 0;
  1266. $info['customNetBalance'] = '0.00';
  1267. $info['showBalancePay'] = 0;
  1268. $info['ghsSalt'] = '';
  1269. $ghsId = intval($info['ghsId'] ?? 0);
  1270. if ($ghsId > 0) {
  1271. $ghsRow = GhsClass::getById($ghsId, true);
  1272. if (!empty($ghsRow)) {
  1273. $info['ghsSalt'] = $ghsRow->salt ?? '';
  1274. $ghsCustomId = intval($ghsRow->customId ?? 0);
  1275. if ($ghsCustomId > 0) {
  1276. $ghsCustom = CustomClass::getById($ghsCustomId, true);
  1277. if (!empty($ghsCustom)) {
  1278. $net = AccountMoneyClass::getNetBalanceFromRow($ghsCustom);
  1279. $info['customNetBalance'] = $net;
  1280. if (bccomp($net, '0', 2) > 0) {
  1281. $info['balance'] = floatval($net);
  1282. $info['showBalancePay'] = 1;
  1283. }
  1284. }
  1285. }
  1286. }
  1287. }
  1288. $getPayType = dict::getDict('getPayType');
  1289. $info['getPayType'] = $getPayType;
  1290. //获取售后条件
  1291. $ghsId = $info['ghsId'] ?? 0;
  1292. $ghsInfo = GhsClass::getById($ghsId, true);
  1293. if (empty($ghsInfo)) {
  1294. util::fail('没有找到供货商');
  1295. }
  1296. $info['afterSale'] = $ghsInfo->afterSale ?? 1;
  1297. //重要,客户看到的电话修改成门店的联系电话
  1298. $ghsShopId = $ghsInfo->shopId ?? 0;
  1299. $ghsShopInfo = ShopClass::getById($ghsShopId, true);
  1300. $info['ghsMobile'] = $ghsShopInfo->telephone ?? '';
  1301. $info['ghsMobile2'] = $ghsShopInfo->telephone2 ?? '';
  1302. $info['hasRenew'] = 1;
  1303. //如果是快捷开单,则不需要显示累计待结,因为商家经常把快捷开单的订单发给客户结账
  1304. $showForPay = 1;
  1305. if ($ghsShopInfo->skCustomId == $info['customId']) {
  1306. $showForPay = 0;
  1307. }
  1308. $info['showForPay'] = $showForPay;
  1309. //冲销单详情页展示"原单"入口:如果当前采购单本身就是一张冲销单(forward==1),
  1310. //通过 xhCg.saleId(对应xhGhsOrder.id) 反查 xhGhsOrderForward 关联记录,
  1311. //拿到原销售单id后再取其 purchaseId 得到花店侧原采购单id,供前端跳转查看原单。ssh 冲销单功能
  1312. $forward = $info['forward'] ?? 0;
  1313. if ($forward == 1) {
  1314. $saleId = $info['saleId'] ?? 0;
  1315. if (!empty($saleId)) {
  1316. $relate = OrderForwardClass::getByForwardOrderId($saleId);
  1317. if (!empty($relate)) {
  1318. $relateOrder = OrderClass::getById($relate['orderId'], true);
  1319. if (!empty($relateOrder)) {
  1320. $info['relateCgId'] = $relateOrder->purchaseId ?? 0;
  1321. $info['relateOrderSn'] = $relate['orderSn'] ?? '';
  1322. }
  1323. }
  1324. }
  1325. }
  1326. util::success($info);
  1327. }
  1328. /**
  1329. * 按采购单查询关联的冲销记录,供 hdApp 售后记录页展示"冲销记录" ssh 冲销单功能
  1330. * xhCg.saleId 指向对应的批发销售单(xhGhsOrder.id),冲销关联记录统一存在 xhGhsOrderForward 表,
  1331. * 花店和供货商两端共用同一张表,这里直接跨命名空间复用 bizGhs\order\classes\OrderForwardClass 查询
  1332. */
  1333. public function actionGetForwardListByOrder()
  1334. {
  1335. $get = Yii::$app->request->get();
  1336. $id = $get['id'] ?? 0;
  1337. $cg = PurchaseClass::getById($id, true);
  1338. if (empty($cg)) {
  1339. util::fail('没有找到采购单');
  1340. }
  1341. if ($cg->mainId != $this->mainId) {
  1342. util::fail('无权查看');
  1343. }
  1344. $saleId = $cg->saleId ?? 0;
  1345. if (empty($saleId)) {
  1346. util::success(['list' => []]);
  1347. }
  1348. $list = OrderForwardClass::getByOrderId($saleId);
  1349. if (empty($list)) {
  1350. util::success(['list' => []]);
  1351. }
  1352. $forwardOrderIds = array_unique(array_filter(array_column($list, 'forwardOrderId')));
  1353. //冲销单在花店侧对应的采购单id(purchaseId),用于点击跳转到 hdApp 的采购单详情
  1354. $forwardOrderInfo = empty($forwardOrderIds) ? [] : OrderClass::getByIds($forwardOrderIds, null, 'id');
  1355. $data = [];
  1356. foreach ($list as $row) {
  1357. $forwardOrder = $forwardOrderInfo[$row['forwardOrderId']] ?? [];
  1358. $data[] = [
  1359. 'forwardCgId' => $forwardOrder['purchaseId'] ?? 0,
  1360. 'forwardOrderSn' => $row['forwardOrderSn'],
  1361. 'forwardPrice' => $row['forwardPrice'],
  1362. 'addTime' => $row['addTime'],
  1363. 'forwardStock' => $forwardOrder['forwardStock'] ?? 1,
  1364. ];
  1365. }
  1366. util::success(['list' => $data]);
  1367. }
  1368. //可用的支付方式 ssh 2021.1.25
  1369. public function actionPayWay()
  1370. {
  1371. $button = [
  1372. ['type' => 'wxPay', 'show' => 1, 'disable' => 1],
  1373. ['type' => 'debtPay', 'show' => 1, 'disable' => 0],
  1374. ['type' => 'balancePay', 'show' => 1, 'disable' => 0],
  1375. ];
  1376. util::success(['button' => $button]);
  1377. }
  1378. //待结款明细 ssh 2021.1.26
  1379. public function actionDebtList()
  1380. {
  1381. $get = Yii::$app->request->get();
  1382. $id = $get['id'] ?? 0;
  1383. $salt = $get['salt'] ?? '';
  1384. $info = GhsClass::getGhsInfo($id);
  1385. if (!empty($salt)) {
  1386. if (!isset($info['salt']) || $info['salt'] != $salt) {
  1387. util::fail('供货商出错了');
  1388. }
  1389. } else {
  1390. if (!isset($info['ownShopId']) || $info['ownShopId'] != $this->shopId) {
  1391. util::fail('错误的供货商.');
  1392. }
  1393. }
  1394. $where = ['ghsId' => $id, 'debt' => PurchaseClass::DEBT_YES];
  1395. $searchTime = $get['searchTime'] ?? '';
  1396. if (!empty($searchTime)) {
  1397. $startTime = $get['startTime'] ?? '';
  1398. $endTime = $get['endTime'] ?? '';
  1399. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  1400. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1401. }
  1402. $respond = PurchaseService::getDebtList($where);
  1403. util::success($respond);
  1404. }
  1405. //支付宝支付 ssh 2021.4.11
  1406. public function actionAliPay()
  1407. {
  1408. ini_set('date.timezone', 'Asia/Shanghai');
  1409. $post = Yii::$app->request->post();
  1410. //默认是支付宝支付
  1411. $payWay = $post['payWay'] ?? 1;
  1412. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1413. $order = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1414. if (empty($order)) {
  1415. util::fail('订单号无效');
  1416. }
  1417. if ($order->status == 5) {
  1418. util::fail('订单已取消');
  1419. }
  1420. if ($order->status != 1) {
  1421. util::fail('订单不是待付款状态');
  1422. }
  1423. $deadline = $order->deadline;
  1424. $current = time();
  1425. if (($current + 50) > strtotime($deadline)) {
  1426. util::fail('订单已失效,请重新下单');
  1427. }
  1428. $ghsId = $order->ghsId ?? 0;
  1429. $ghs = GhsClass::getById($ghsId, true);
  1430. if (empty($ghs)) {
  1431. util::fail('没有供货商信息');
  1432. }
  1433. $ghsShopId = $ghs->shopId ?? 0;
  1434. $ghsShop = ShopClass::getById($ghsShopId, true);
  1435. if (empty($ghsShop)) {
  1436. util::fail('没有供货商门店信息');
  1437. }
  1438. if (isset($ghsShop->lklSjNo) && empty($ghsShop->lklSjNo)) {
  1439. util::fail('商家支付功能未开通');
  1440. }
  1441. //避免重复提交
  1442. util::checkRepeatCommit($orderSn, 8);
  1443. //已经唤起过支付了,根据拉卡拉的规则,需要生成新的订单号
  1444. if ($order->changePrice == 2) {
  1445. $oldOrderSn = $orderSn;
  1446. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1447. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1448. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1449. $params = [
  1450. 'appid' => 'OP00002119',
  1451. 'serial_no' => '018b08cfddbd',
  1452. 'merchant_no' => $ghsShop->lklSjNo,
  1453. 'term_no' => $ghsShop->lklScanTermNo,
  1454. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1455. 'lklCertificatePath' => $lklCertificatePath,
  1456. ];
  1457. $laResource = new Lakala($params);
  1458. $closeParams = [
  1459. 'orderSn' => $oldOrderSn,
  1460. ];
  1461. $response = $laResource->cashClose($closeParams);
  1462. if (isset($response['code']) == false || $response['code'] != '000000') {
  1463. $msg = $response['msg'] ?? '';
  1464. $code = $response['code'] ?? 0;
  1465. if (!in_array($code, ['000091'])) {
  1466. noticeUtil::push('注意花店买花更换单号:' . $oldOrderSn . ',关单没有成功(收银台-支付宝),' . $msg, '15280215347');
  1467. }
  1468. }
  1469. $shopId = $order->shopId ?? 0;
  1470. $mainId = $order->mainId ?? 0;
  1471. $customId = $order->customId ?? 0;
  1472. $ghsId = $order->ghsId ?? 0;
  1473. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'customId' => $customId, 'ghsId' => $ghsId];
  1474. $newOrderSn = orderSn::getPurchaseSn($snData);
  1475. $orderSn = $newOrderSn;
  1476. $order->orderSn = $newOrderSn;
  1477. $order->save();
  1478. PurchaseItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $newOrderSn]);
  1479. }
  1480. $order->changePrice = 2;
  1481. $order->save();
  1482. $ghsShopName = $ghsShop->shopName ?? '';
  1483. //要带上哪个店的,这样才知道客户下的单是哪个店的,客户很多有多家店
  1484. $name = $ghsShopName . " 花材 " . $orderSn;
  1485. $totalFee = $order->realPrice;
  1486. $purchaseCapital = dict::getDict('capitalType', 'xhPurchase', 'id');
  1487. $ghsId = $order->ghsId ?? 0;
  1488. $ghs = GhsClass::getById($ghsId, true);
  1489. if (empty($ghs)) {
  1490. util::fail('没有供货商信息');
  1491. }
  1492. $ghsShopId = $ghs->shopId ?? 0;
  1493. $ghsShop = ShopClass::getById($ghsShopId, true);
  1494. if (empty($ghsShop)) {
  1495. util::fail('没有供货商门店信息');
  1496. }
  1497. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1498. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1499. $params = [
  1500. 'appid' => 'OP00002119',
  1501. 'serial_no' => '018b08cfddbd',
  1502. 'merchant_no' => $ghsShop->lklSjNo,
  1503. 'term_no' => $ghsShop->lklB2BTermNo,
  1504. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1505. 'lklCertificatePath' => $lklCertificatePath,
  1506. ];
  1507. $laResource = new Lakala($params);
  1508. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/cash-pay-callback";
  1509. $wxParams = [
  1510. 'orderSn' => $orderSn,
  1511. 'amount' => $totalFee,
  1512. 'capitalType' => $purchaseCapital,
  1513. 'notifyUrl' => $notifyUrl,
  1514. 'subject' => $name,
  1515. 'payWay' => $payWay,
  1516. ];
  1517. $response = $laResource->cashierPay($wxParams);
  1518. if (isset($response['code']) == false || $response['code'] != '000000') {
  1519. $errMsg = $response['msg'] ?? '';
  1520. noticeUtil::push('编号AA90:' . $errMsg, '15280215347');
  1521. util::fail('发起支付失败');
  1522. }
  1523. $counter_url = $response['resp_data']['counter_url'] ? $response['resp_data']['counter_url'] : '';
  1524. $hasRenew = $ghsShop->hasRenew ?? 0;
  1525. $new = [
  1526. 'payUrl' => $counter_url,
  1527. 'orderSn' => $orderSn,
  1528. 'hasRenew' => 1,
  1529. ];
  1530. util::success($new);
  1531. }
  1532. //微信支付 ssh 2021.4.11
  1533. public function actionWxPay()
  1534. {
  1535. ini_set('date.timezone', 'Asia/Shanghai');
  1536. $post = Yii::$app->request->post();
  1537. $couponId = $post['couponId'] ?? 0;
  1538. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1539. $order = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1540. if (empty($order)) {
  1541. util::fail('订单号无效');
  1542. }
  1543. if ($order->status == 5) {
  1544. util::fail('订单已取消');
  1545. }
  1546. if ($order->status != 1) {
  1547. util::fail('订单不是待付款状态');
  1548. }
  1549. $deadline = $order->deadline;
  1550. $current = time();
  1551. if (($current + 50) > strtotime($deadline)) {
  1552. util::fail('订单已失效,请重新下单');
  1553. }
  1554. //避免重复提交
  1555. util::checkRepeatCommit($orderSn, 8);
  1556. $ghsId = $order->ghsId ?? 0;
  1557. $ghs = GhsClass::getById($ghsId, true);
  1558. if (empty($ghs)) {
  1559. util::fail('没有供货商信息');
  1560. }
  1561. $ghsShopId = $ghs->shopId ?? 0;
  1562. $ghsShop = ShopClass::getById($ghsShopId, true);
  1563. if (empty($ghsShop)) {
  1564. util::fail('没有供货商门店信息');
  1565. }
  1566. if (isset($ghsShop->lklSjNo) && empty($ghsShop->lklSjNo)) {
  1567. util::fail('商家支付功能未开通');
  1568. }
  1569. //已经唤起过微信支付了,根据拉卡拉的规则,需要生成新的订单号
  1570. if ($order->changePrice == 2) {
  1571. $oldOrderSn = $orderSn;
  1572. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1573. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1574. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1575. $params = [
  1576. 'appid' => 'OP00002119',
  1577. 'serial_no' => '018b08cfddbd',
  1578. 'merchant_no' => $ghsShop->lklSjNo,
  1579. 'term_no' => $ghsShop->lklScanTermNo,
  1580. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1581. 'lklCertificatePath' => $lklCertificatePath,
  1582. ];
  1583. $laResource = new Lakala($params);
  1584. $closeParams = [
  1585. 'orderSn' => $oldOrderSn,
  1586. ];
  1587. $response = $laResource->close($closeParams);
  1588. if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
  1589. $msg = $response['msg'] ?? '';
  1590. $code = $response['code'] ?? 0;
  1591. if (!in_array($code, ['BBS11114'])) {
  1592. noticeUtil::push('重点注意,花店买花更换单号没有成功,单号:' . $oldOrderSn . ',关单没有成功,' . $msg . $code, '15280215347');
  1593. util::fail('出错了,请重新下单');
  1594. }
  1595. }
  1596. $shopId = $order->shopId ?? 0;
  1597. $mainId = $order->mainId ?? 0;
  1598. $customId = $order->customId ?? 0;
  1599. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'customId' => $customId, 'ghsId' => $ghsId];
  1600. $newOrderSn = orderSn::getPurchaseSn($snData);
  1601. $orderSn = $newOrderSn;
  1602. $order->orderSn = $newOrderSn;
  1603. $order->save();
  1604. PurchaseItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $newOrderSn]);
  1605. }
  1606. $id = $order->id;
  1607. $order->changePrice = 2;
  1608. $order->save();
  1609. $ghsShopName = $ghsShop->shopName ?? '';
  1610. //要带上哪个店的,这样才知道客户下的单是哪个店的,客户很多有多家店
  1611. $name = $ghsShopName . " 花材 " . $orderSn;
  1612. $totalFee = $order->realPrice;
  1613. $openId = '';
  1614. if (isset($post['currentMiniOpenId']) && !empty($post['currentMiniOpenId'])) {
  1615. $openId = $post['currentMiniOpenId'];
  1616. //noticeUtil::push('花店采购下单时,通过前端获取了openId:' . $openId, '15280215347');
  1617. }
  1618. if (empty($openId)) {
  1619. if (isset($this->admin) && !empty($this->admin)) {
  1620. if (isset($this->admin->miniOpenId) && !empty($this->admin->miniOpenId)) {
  1621. $openId = $this->admin->miniOpenId;
  1622. noticeUtil::push('花店采购下单时,通过数据库获取了openId:' . $openId, '15280215347');
  1623. }
  1624. }
  1625. }
  1626. if (empty($openId)) {
  1627. $currentShopId = $order->shopId ?? 0;
  1628. $currentShop = ShopClass::getById($currentShopId, true);
  1629. $currentShopName = $currentShop->merchantName . ' ' . $currentShop->shopName;
  1630. $currentMobile = $currentShop->mobile ?? '';
  1631. noticeUtil::push("花店采购时,发现没有openId,请跟进是否采购成功。{$currentShopName} {$currentMobile}", '15280215347');
  1632. util::success(['hasError' => 1, 'hasNoMiniOpenId' => 1]);
  1633. }
  1634. $purchaseCapital = dict::getDict('capitalType', 'xhPurchase', 'id');
  1635. //花卉宝代为申请的微信支付
  1636. $merchantExtend = WxOpenClass::getWxInfo();
  1637. if (empty($ghsShop->lklSjNo)) {
  1638. noticeUtil::push('编号31505:单号:' . $orderSn . ' 商家没有开通收款功能:' . $ghsShopName, '15280215347');
  1639. util::fail('商家未开通支付功能');
  1640. }
  1641. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1642. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1643. $params = [
  1644. 'appid' => 'OP00002119',
  1645. 'serial_no' => '018b08cfddbd',
  1646. 'merchant_no' => $ghsShop->lklSjNo,
  1647. 'term_no' => $ghsShop->lklScanTermNo,
  1648. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1649. 'lklCertificatePath' => $lklCertificatePath,
  1650. ];
  1651. $laResource = new Lakala($params);
  1652. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  1653. $wxParams = [
  1654. 'orderSn' => $orderSn,
  1655. 'amount' => $totalFee,
  1656. 'capitalType' => $purchaseCapital,
  1657. 'notifyUrl' => $notifyUrl,
  1658. 'wxAppId' => $merchantExtend['miniAppId'],
  1659. 'openId' => $openId,
  1660. 'subject' => $name,
  1661. 'couponId' => $couponId,
  1662. ];
  1663. $response = $laResource->driveWxPay($wxParams);
  1664. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1665. $errMsg = $response['msg'] ?? '';
  1666. noticeUtil::push('编号129680931:' . $errMsg . ' 单号:' . $orderSn . ' ' . $ghsShopName, '15280215347');
  1667. util::fail('支付失败');
  1668. }
  1669. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  1670. $appId = $newParams['app_id'] ?? '';
  1671. $nonceStr = $newParams['nonce_str'] ?? '';
  1672. $paySign = $newParams['pay_sign'] ?? '';
  1673. $package = $newParams['package'] ?? '';
  1674. $signType = $newParams['sign_type'] ?? '';
  1675. $timeStamp = $newParams['time_stamp'] ?? '';
  1676. $new = [
  1677. 'id' => $id,
  1678. 'appId' => $appId,
  1679. 'nonceStr' => $nonceStr,
  1680. 'paySign' => $paySign,
  1681. 'package' => $package,
  1682. 'signType' => $signType,
  1683. 'timeStamp' => $timeStamp,
  1684. 'orderSn' => $orderSn,
  1685. ];
  1686. util::success($new);
  1687. }
  1688. //计算运费 ssh 20221003
  1689. public function actionFreight()
  1690. {
  1691. $get = Yii::$app->request->get();
  1692. $shop = $this->shop;
  1693. $ghsId = $get['ghsId'] ?? 0;
  1694. $ghs = GhsClass::getById($ghsId, true);
  1695. if (empty($ghs)) {
  1696. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1697. }
  1698. $ghsShopId = $ghs->shopId ?? 0;
  1699. $ghsShop = ShopClass::getById($ghsShopId, true);
  1700. if (empty($ghsShop)) {
  1701. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1702. }
  1703. $customId = $ghs->customId ?? 0;
  1704. $custom = CustomClass::getById($customId, true);
  1705. if (empty($custom)) {
  1706. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1707. }
  1708. $weight = $get['weight'] ?? 0;
  1709. if (empty($weight)) {
  1710. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1711. }
  1712. $respond = PurchaseClass::getDistanceFee($shop, $ghsShop, $weight, $custom);
  1713. util::success($respond);
  1714. }
  1715. //运费计算 lqh 2021.4.12 暂时返回固定值
  1716. public function actionFreight2()
  1717. {
  1718. //lqh 2021.6.25 运费固定返回0
  1719. util::success(['sedCost' => 0]);
  1720. }
  1721. }