PurchaseController.php 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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. //标记当配送方式已收一次包装费/运费,只要有成功单就标记,后续不再重复要求门槛或加收费用
  963. $current = date("Y_m_d");
  964. if (isset($info->sendType)) {
  965. $key = 'ghs_custom_today_has_get_pack_cost_' . $info->sendType . '_' . $current . '_' . $customId;
  966. Yii::$app->redis->executeCommand('SETEX', [$key, 86400, '1']);
  967. // 兼容快递/送货/跑腿收运费或限制下单的情况
  968. $sendKey = 'ghs_custom_today_has_get_send_cost_' . $info->sendType . '_' . $current . '_' . $customId;
  969. Yii::$app->redis->executeCommand('SETEX', [$sendKey, 86400, '1']);
  970. }
  971. }
  972. // 复杂分支/关键逻辑:不是预订单,且供货商配置为直接完成流程,则自动确认收货。
  973. // 优化:复用已有的 $info 实例,避免重复查询;同时将自动确认收货包裹在独立事务中,合并批量写操作,减少磁盘 I/O。
  974. if (!empty($info)) {
  975. if (isset($info->book) && $info->book == 0) {
  976. $ghsShopId = $ghs['shopId'] ?? 0;
  977. $ext = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,orderFlow');
  978. if (!empty($ext) && intval($ext->orderFlow ?? 0) === 0) {
  979. $takeTransaction = Yii::$app->db->beginTransaction();
  980. try {
  981. PurchaseClass::confirmTake($info);
  982. $takeTransaction->commit();
  983. } catch (\Exception $takeEx) {
  984. $takeTransaction->rollBack();
  985. Yii::error("自动确认收货失败: " . $takeEx->getMessage());
  986. throw $takeEx;
  987. }
  988. }
  989. }
  990. }
  991. //app新订单通知
  992. $saleId = $info->saleId ?? 0;
  993. $order = OrderClass::getById($saleId, true);
  994. if (!empty($order)) {
  995. $shopId = $order->shopId ?? 0;
  996. $shop = ShopClass::getById($shopId, true);
  997. if (!empty($shop)) {
  998. //通知供货商
  999. GhsNotifyClass::newOrderNotify($saleId);
  1000. }
  1001. //订单生成时唤起在线打印
  1002. if (isset($order->needPrint) && $order->needPrint == dict::getDict('needPrint', 'need')) {
  1003. //有几个地方要同步去修改
  1004. if (getenv('YII_ENV') == 'production') {
  1005. //源花汇、盛丰不自动打小票,关键词mall_order_no_auto_print
  1006. $mallOrderNoPrint = [10536, 44282, 26374];
  1007. } else {
  1008. $mallOrderNoPrint = [];
  1009. }
  1010. if (!in_array($order->mainId, $mallOrderNoPrint)) {
  1011. // 复杂分支/关键逻辑:优化:只查询一次 $ext,合并 $order->save(),减少数据库交互
  1012. $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  1013. $hasPrintSn = isset($ext->printSn) && !empty($ext->printSn);
  1014. OrderClass::onlinePrint($order);
  1015. if ($hasPrintSn) {
  1016. $order->printNum += 1;
  1017. }
  1018. //花镜 打二次小票,有多处要修改搜索关键词tow_print
  1019. if (in_array($order->mainId, [76796])) {
  1020. OrderClass::onlinePrint($order);
  1021. if ($hasPrintSn) {
  1022. $order->printNum += 1;
  1023. }
  1024. }
  1025. if ($hasPrintSn) {
  1026. $order->save();
  1027. }
  1028. }
  1029. }
  1030. //付款成功之后呼叫跑腿,关键词 pay_after_call_pt,多处要同步修改
  1031. GhsDeliveryOrderClass::payAfter($order);
  1032. // 复杂分支/关键逻辑:优化:使用 updateByCondition 直接更新最后下单时间,避免先 SELECT 再 UPDATE 的性能开销
  1033. $customId = $order->customId ?? 0;
  1034. $ghsId = $order->ghsId ?? 0;
  1035. $date = date("Y-m-d H:i:s");
  1036. if ($customId > 0) {
  1037. CustomClass::updateByCondition(['id' => $customId], ['recentExpend' => $date]);
  1038. }
  1039. if ($ghsId > 0) {
  1040. GhsClass::updateByCondition(['id' => $ghsId], ['recentExpend' => $date]);
  1041. }
  1042. }
  1043. } catch (\Exception $e) {
  1044. $transaction->rollBack();
  1045. Yii::error("赊账支付失败原因:" . $e->getMessage());
  1046. util::fail('支付失败');
  1047. }
  1048. util::success($info->attributes);
  1049. }
  1050. /**
  1051. * 采购待支付页:客户 xhGhsCustom 净余额支付(并发重试 + 行锁)。
  1052. */
  1053. public function actionCustomBalancePay()
  1054. {
  1055. $post = Yii::$app->request->post();
  1056. $orderSn = $post['orderSn'] ?? '';
  1057. if (empty($orderSn)) {
  1058. util::fail('订单号无效');
  1059. }
  1060. $cacheKey = 'hd_custom_balance_pay_' . $orderSn;
  1061. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1062. if (!empty($has)) {
  1063. util::fail('请稍等...');
  1064. }
  1065. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 8, 'has']);
  1066. $info = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1067. if (empty($info)) {
  1068. util::fail('没有找到采购单');
  1069. }
  1070. PurchaseService::valid($info, $this->shopId);
  1071. $deadline = $info->deadline ?? '';
  1072. if (!empty($deadline) && time() > strtotime($deadline)) {
  1073. util::fail('订单已失效了哦');
  1074. }
  1075. $ghsId = intval($info->ghsId ?? 0);
  1076. $ghs = GhsClass::getGhsInfo($ghsId);
  1077. try {
  1078. $result = util::runWithDbConcurrencyRetry(function () use ($orderSn) {
  1079. $connection = Yii::$app->db;
  1080. $transaction = $connection->beginTransaction();
  1081. try {
  1082. $purchase = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1083. $respond = PurchaseService::payByGhsCustomBalance($purchase);
  1084. $transaction->commit();
  1085. return $respond;
  1086. } catch (\Exception $exception) {
  1087. if ($transaction->isActive) {
  1088. $transaction->rollBack();
  1089. }
  1090. throw $exception;
  1091. }
  1092. });
  1093. $info = $result['purchase'];
  1094. $order = $result['saleOrder'] ?? null;
  1095. if (!empty($order)) {
  1096. if (isset($info->book) && $info->book == 0 && !empty($ghs)) {
  1097. $ghsShopId = $ghs['shopId'] ?? 0;
  1098. $ext = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,orderFlow');
  1099. if (!empty($ext) && intval($ext->orderFlow ?? 0) === 0) {
  1100. $cg = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1101. if (!empty($cg)) {
  1102. PurchaseClass::confirmTake($cg);
  1103. }
  1104. }
  1105. }
  1106. $shopId = $order->shopId ?? 0;
  1107. $shop = ShopClass::getById($shopId, true);
  1108. if (!empty($shop)) {
  1109. GhsNotifyClass::newOrderNotify($order->id ?? 0);
  1110. }
  1111. if (isset($order->needPrint) && $order->needPrint == dict::getDict('needPrint', 'need')) {
  1112. $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. //待结款明细 ssh 2021.1.26
  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. $respond = PurchaseService::getDebtList($where);
  1423. util::success($respond);
  1424. }
  1425. //支付宝支付 ssh 2021.4.11
  1426. public function actionAliPay()
  1427. {
  1428. ini_set('date.timezone', 'Asia/Shanghai');
  1429. $post = Yii::$app->request->post();
  1430. //默认是支付宝支付
  1431. $payWay = $post['payWay'] ?? 1;
  1432. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1433. $order = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1434. if (empty($order)) {
  1435. util::fail('订单号无效');
  1436. }
  1437. if ($order->status == 5) {
  1438. util::fail('订单已取消');
  1439. }
  1440. if ($order->status != 1) {
  1441. util::fail('订单不是待付款状态');
  1442. }
  1443. $deadline = $order->deadline;
  1444. $current = time();
  1445. if (($current + 50) > strtotime($deadline)) {
  1446. util::fail('订单已失效,请重新下单');
  1447. }
  1448. $ghsId = $order->ghsId ?? 0;
  1449. $ghs = GhsClass::getById($ghsId, true);
  1450. if (empty($ghs)) {
  1451. util::fail('没有供货商信息');
  1452. }
  1453. $ghsShopId = $ghs->shopId ?? 0;
  1454. $ghsShop = ShopClass::getById($ghsShopId, true);
  1455. if (empty($ghsShop)) {
  1456. util::fail('没有供货商门店信息');
  1457. }
  1458. if (isset($ghsShop->lklSjNo) && empty($ghsShop->lklSjNo)) {
  1459. util::fail('商家支付功能未开通');
  1460. }
  1461. //避免重复提交
  1462. util::checkRepeatCommit($orderSn, 8);
  1463. //已经唤起过支付了,根据拉卡拉的规则,需要生成新的订单号
  1464. if ($order->changePrice == 2) {
  1465. $oldOrderSn = $orderSn;
  1466. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1467. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1468. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1469. $params = [
  1470. 'appid' => 'OP00002119',
  1471. 'serial_no' => '018b08cfddbd',
  1472. 'merchant_no' => $ghsShop->lklSjNo,
  1473. 'term_no' => $ghsShop->lklScanTermNo,
  1474. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1475. 'lklCertificatePath' => $lklCertificatePath,
  1476. ];
  1477. $laResource = new Lakala($params);
  1478. $closeParams = [
  1479. 'orderSn' => $oldOrderSn,
  1480. ];
  1481. $response = $laResource->cashClose($closeParams);
  1482. if (isset($response['code']) == false || $response['code'] != '000000') {
  1483. $msg = $response['msg'] ?? '';
  1484. $code = $response['code'] ?? 0;
  1485. if (!in_array($code, ['000091'])) {
  1486. noticeUtil::push('注意花店买花更换单号:' . $oldOrderSn . ',关单没有成功(收银台-支付宝),' . $msg, '15280215347');
  1487. }
  1488. }
  1489. $shopId = $order->shopId ?? 0;
  1490. $mainId = $order->mainId ?? 0;
  1491. $customId = $order->customId ?? 0;
  1492. $ghsId = $order->ghsId ?? 0;
  1493. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'customId' => $customId, 'ghsId' => $ghsId];
  1494. $newOrderSn = orderSn::getPurchaseSn($snData);
  1495. $orderSn = $newOrderSn;
  1496. $order->orderSn = $newOrderSn;
  1497. $order->save();
  1498. PurchaseItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $newOrderSn]);
  1499. }
  1500. $order->changePrice = 2;
  1501. $order->save();
  1502. $ghsShopName = $ghsShop->shopName ?? '';
  1503. //要带上哪个店的,这样才知道客户下的单是哪个店的,客户很多有多家店
  1504. $name = $ghsShopName . " 花材 " . $orderSn;
  1505. $totalFee = $order->realPrice;
  1506. $purchaseCapital = dict::getDict('capitalType', 'xhPurchase', 'id');
  1507. $ghsId = $order->ghsId ?? 0;
  1508. $ghs = GhsClass::getById($ghsId, true);
  1509. if (empty($ghs)) {
  1510. util::fail('没有供货商信息');
  1511. }
  1512. $ghsShopId = $ghs->shopId ?? 0;
  1513. $ghsShop = ShopClass::getById($ghsShopId, true);
  1514. if (empty($ghsShop)) {
  1515. util::fail('没有供货商门店信息');
  1516. }
  1517. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1518. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1519. $params = [
  1520. 'appid' => 'OP00002119',
  1521. 'serial_no' => '018b08cfddbd',
  1522. 'merchant_no' => $ghsShop->lklSjNo,
  1523. 'term_no' => $ghsShop->lklB2BTermNo,
  1524. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1525. 'lklCertificatePath' => $lklCertificatePath,
  1526. ];
  1527. $laResource = new Lakala($params);
  1528. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/cash-pay-callback";
  1529. $wxParams = [
  1530. 'orderSn' => $orderSn,
  1531. 'amount' => $totalFee,
  1532. 'capitalType' => $purchaseCapital,
  1533. 'notifyUrl' => $notifyUrl,
  1534. 'subject' => $name,
  1535. 'payWay' => $payWay,
  1536. ];
  1537. $response = $laResource->cashierPay($wxParams);
  1538. if (isset($response['code']) == false || $response['code'] != '000000') {
  1539. $errMsg = $response['msg'] ?? '';
  1540. noticeUtil::push('编号AA90:' . $errMsg, '15280215347');
  1541. util::fail('发起支付失败');
  1542. }
  1543. $counter_url = $response['resp_data']['counter_url'] ? $response['resp_data']['counter_url'] : '';
  1544. $hasRenew = $ghsShop->hasRenew ?? 0;
  1545. $new = [
  1546. 'payUrl' => $counter_url,
  1547. 'orderSn' => $orderSn,
  1548. 'hasRenew' => 1,
  1549. ];
  1550. util::success($new);
  1551. }
  1552. //微信支付 ssh 2021.4.11
  1553. public function actionWxPay()
  1554. {
  1555. ini_set('date.timezone', 'Asia/Shanghai');
  1556. $post = Yii::$app->request->post();
  1557. $couponId = $post['couponId'] ?? 0;
  1558. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1559. $order = PurchaseClass::getByCondition(['orderSn' => $orderSn], true);
  1560. if (empty($order)) {
  1561. util::fail('订单号无效');
  1562. }
  1563. if ($order->status == 5) {
  1564. util::fail('订单已取消');
  1565. }
  1566. if ($order->status != 1) {
  1567. util::fail('订单不是待付款状态');
  1568. }
  1569. $deadline = $order->deadline;
  1570. $current = time();
  1571. if (($current + 50) > strtotime($deadline)) {
  1572. util::fail('订单已失效,请重新下单');
  1573. }
  1574. //避免重复提交
  1575. util::checkRepeatCommit($orderSn, 8);
  1576. $ghsId = $order->ghsId ?? 0;
  1577. $ghs = GhsClass::getById($ghsId, true);
  1578. if (empty($ghs)) {
  1579. util::fail('没有供货商信息');
  1580. }
  1581. $ghsShopId = $ghs->shopId ?? 0;
  1582. $ghsShop = ShopClass::getById($ghsShopId, true);
  1583. if (empty($ghsShop)) {
  1584. util::fail('没有供货商门店信息');
  1585. }
  1586. if (isset($ghsShop->lklSjNo) && empty($ghsShop->lklSjNo)) {
  1587. util::fail('商家支付功能未开通');
  1588. }
  1589. //已经唤起过微信支付了,根据拉卡拉的规则,需要生成新的订单号
  1590. if ($order->changePrice == 2) {
  1591. $oldOrderSn = $orderSn;
  1592. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1593. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1594. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1595. $params = [
  1596. 'appid' => 'OP00002119',
  1597. 'serial_no' => '018b08cfddbd',
  1598. 'merchant_no' => $ghsShop->lklSjNo,
  1599. 'term_no' => $ghsShop->lklScanTermNo,
  1600. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1601. 'lklCertificatePath' => $lklCertificatePath,
  1602. ];
  1603. $laResource = new Lakala($params);
  1604. $closeParams = [
  1605. 'orderSn' => $oldOrderSn,
  1606. ];
  1607. $response = $laResource->close($closeParams);
  1608. if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
  1609. $msg = $response['msg'] ?? '';
  1610. $code = $response['code'] ?? 0;
  1611. if (!in_array($code, ['BBS11114'])) {
  1612. noticeUtil::push('重点注意,花店买花更换单号没有成功,单号:' . $oldOrderSn . ',关单没有成功,' . $msg . $code, '15280215347');
  1613. util::fail('出错了,请重新下单');
  1614. }
  1615. }
  1616. $shopId = $order->shopId ?? 0;
  1617. $mainId = $order->mainId ?? 0;
  1618. $customId = $order->customId ?? 0;
  1619. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'customId' => $customId, 'ghsId' => $ghsId];
  1620. $newOrderSn = orderSn::getPurchaseSn($snData);
  1621. $orderSn = $newOrderSn;
  1622. $order->orderSn = $newOrderSn;
  1623. $order->save();
  1624. PurchaseItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $newOrderSn]);
  1625. }
  1626. $id = $order->id;
  1627. $order->changePrice = 2;
  1628. $order->save();
  1629. $ghsShopName = $ghsShop->shopName ?? '';
  1630. //要带上哪个店的,这样才知道客户下的单是哪个店的,客户很多有多家店
  1631. $name = $ghsShopName . " 花材 " . $orderSn;
  1632. $totalFee = $order->realPrice;
  1633. $openId = '';
  1634. if (isset($post['currentMiniOpenId']) && !empty($post['currentMiniOpenId'])) {
  1635. $openId = $post['currentMiniOpenId'];
  1636. //noticeUtil::push('花店采购下单时,通过前端获取了openId:' . $openId, '15280215347');
  1637. }
  1638. if (empty($openId)) {
  1639. if (isset($this->admin) && !empty($this->admin)) {
  1640. if (isset($this->admin->miniOpenId) && !empty($this->admin->miniOpenId)) {
  1641. $openId = $this->admin->miniOpenId;
  1642. noticeUtil::push('花店采购下单时,通过数据库获取了openId:' . $openId, '15280215347');
  1643. }
  1644. }
  1645. }
  1646. if (empty($openId)) {
  1647. $currentShopId = $order->shopId ?? 0;
  1648. $currentShop = ShopClass::getById($currentShopId, true);
  1649. $currentShopName = $currentShop->merchantName . ' ' . $currentShop->shopName;
  1650. $currentMobile = $currentShop->mobile ?? '';
  1651. noticeUtil::push("花店采购时,发现没有openId,请跟进是否采购成功。{$currentShopName} {$currentMobile}", '15280215347');
  1652. util::success(['hasError' => 1, 'hasNoMiniOpenId' => 1]);
  1653. }
  1654. $purchaseCapital = dict::getDict('capitalType', 'xhPurchase', 'id');
  1655. //花卉宝代为申请的微信支付
  1656. $merchantExtend = WxOpenClass::getWxInfo();
  1657. if (empty($ghsShop->lklSjNo)) {
  1658. noticeUtil::push('编号31505:单号:' . $orderSn . ' 商家没有开通收款功能:' . $ghsShopName, '15280215347');
  1659. util::fail('商家未开通支付功能');
  1660. }
  1661. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1662. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1663. $params = [
  1664. 'appid' => 'OP00002119',
  1665. 'serial_no' => '018b08cfddbd',
  1666. 'merchant_no' => $ghsShop->lklSjNo,
  1667. 'term_no' => $ghsShop->lklScanTermNo,
  1668. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1669. 'lklCertificatePath' => $lklCertificatePath,
  1670. ];
  1671. $laResource = new Lakala($params);
  1672. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  1673. $wxParams = [
  1674. 'orderSn' => $orderSn,
  1675. 'amount' => $totalFee,
  1676. 'capitalType' => $purchaseCapital,
  1677. 'notifyUrl' => $notifyUrl,
  1678. 'wxAppId' => $merchantExtend['miniAppId'],
  1679. 'openId' => $openId,
  1680. 'subject' => $name,
  1681. 'couponId' => $couponId,
  1682. ];
  1683. $response = $laResource->driveWxPay($wxParams);
  1684. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1685. $errMsg = $response['msg'] ?? '';
  1686. noticeUtil::push('编号129680931:' . $errMsg . ' 单号:' . $orderSn . ' ' . $ghsShopName, '15280215347');
  1687. util::fail('支付失败');
  1688. }
  1689. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  1690. $appId = $newParams['app_id'] ?? '';
  1691. $nonceStr = $newParams['nonce_str'] ?? '';
  1692. $paySign = $newParams['pay_sign'] ?? '';
  1693. $package = $newParams['package'] ?? '';
  1694. $signType = $newParams['sign_type'] ?? '';
  1695. $timeStamp = $newParams['time_stamp'] ?? '';
  1696. $new = [
  1697. 'id' => $id,
  1698. 'appId' => $appId,
  1699. 'nonceStr' => $nonceStr,
  1700. 'paySign' => $paySign,
  1701. 'package' => $package,
  1702. 'signType' => $signType,
  1703. 'timeStamp' => $timeStamp,
  1704. 'orderSn' => $orderSn,
  1705. ];
  1706. util::success($new);
  1707. }
  1708. //计算运费 ssh 20221003
  1709. public function actionFreight()
  1710. {
  1711. $get = Yii::$app->request->get();
  1712. $shop = $this->shop;
  1713. $ghsId = $get['ghsId'] ?? 0;
  1714. $ghs = GhsClass::getById($ghsId, true);
  1715. if (empty($ghs)) {
  1716. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1717. }
  1718. $ghsShopId = $ghs->shopId ?? 0;
  1719. $ghsShop = ShopClass::getById($ghsShopId, true);
  1720. if (empty($ghsShop)) {
  1721. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1722. }
  1723. $customId = $ghs->customId ?? 0;
  1724. $custom = CustomClass::getById($customId, true);
  1725. if (empty($custom)) {
  1726. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1727. }
  1728. $weight = $get['weight'] ?? 0;
  1729. if (empty($weight)) {
  1730. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  1731. }
  1732. $respond = PurchaseClass::getDistanceFee($shop, $ghsShop, $weight, $custom);
  1733. util::success($respond);
  1734. }
  1735. //运费计算 lqh 2021.4.12 暂时返回固定值
  1736. public function actionFreight2()
  1737. {
  1738. //lqh 2021.6.25 运费固定返回0
  1739. util::success(['sedCost' => 0]);
  1740. }
  1741. }