OrderController.php 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135
  1. <?php
  2. namespace mall\controllers;
  3. use biz\product\classes\ProductClass;
  4. use biz\shop\classes\ShopClass;
  5. use biz\wx\classes\WxMessageClass;
  6. use bizHd\groupBuy\classes\GroupBuyClass;
  7. use bizHd\custom\classes\HdClass;
  8. use bizHd\distribution\classes\DistributionOrderClass;
  9. use bizHd\express\classes\HdDeliveryOrderClass;
  10. use bizHd\order\classes\OrderClass as HdOrderClass;
  11. use bizHd\order\classes\PsMethodClass;
  12. use bizHd\order\classes\WholeOrderDiscountClass;
  13. use bizHd\refund\classes\HdRefundClass;
  14. use bizHd\refund\classes\HdRefundMallClass;
  15. use bizHd\hb\classes\HbClass;
  16. use bizHd\hb\classes\HbScopeClass;
  17. use bizHd\homePageConfig\classes\HomePageModuleClass;
  18. use bizHd\order\classes\ScanPayClass;
  19. use bizHd\wx\classes\WxOpenClass;
  20. use bizMall\custom\classes\CustomClass;
  21. use bizMall\goods\classes\GoodsClass;
  22. use bizMall\order\classes\OrderClass;
  23. use bizMall\order\classes\OrderForwardClass;
  24. use bizMall\order\classes\OrderItemClass;
  25. use bizMall\order\services\OrderService;
  26. use bizMall\promote\services\CouponService;
  27. use bizMall\saas\services\RegionService;
  28. use bizMall\shop\classes\ShopExtClass;
  29. use bizMall\user\services\UserService;
  30. use common\components\dateUtil;
  31. use common\components\delivery\util\DeliveryQuoteUtil;
  32. use common\components\dict;
  33. use common\components\errCode;
  34. use common\components\imgUtil;
  35. use common\components\mapUtil;
  36. use common\components\noticeUtil;
  37. use common\components\orderSn;
  38. use common\components\stringUtil;
  39. use Yii;
  40. use common\components\util;
  41. use common\components\lakala\Lakala;
  42. use common\components\IntraCityExpress;
  43. class OrderController extends BaseController
  44. {
  45. //二维码收款使用
  46. public $guestAccess = ['order-relate', 'fast-pay'];
  47. public function actionInform()
  48. {
  49. $get = Yii::$app->request->get();
  50. $hdId = $get['hdId'] ?? 0;
  51. $account = $get['account'] ?? 0;
  52. $page = $get['page'] ?? '';
  53. $userId = $this->userId;
  54. noticeUtil::push("零售客户下单报错 hdId:{$hdId} account:{$account} userId:{$userId} page:{$page}", '15280215347');
  55. }
  56. //记账单列表 ssh 20250627
  57. public function actionDebtList()
  58. {
  59. $get = Yii::$app->request->get();
  60. $id = $get['id'] ?? 0;
  61. $where = [];
  62. $where['userId'] = $this->userId;
  63. if (!empty($id)) {
  64. $hd = \bizMall\hd\classes\HdClass::getById($id, true);
  65. if (empty($hd)) {
  66. util::fail('无效的花店');
  67. }
  68. $where['hdId'] = $id;
  69. }
  70. $where['debt'] = 1;
  71. $searchTime = $get['searchTime'] ?? '';
  72. if (!empty($searchTime)) {
  73. $startTime = $get['startTime'] ?? '';
  74. $endTime = $get['endTime'] ?? '';
  75. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  76. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  77. }
  78. $respond = OrderClass::getDebtList($where);
  79. util::success($respond);
  80. }
  81. //新计算运费
  82. public function actionNewFreight()
  83. {
  84. $post = Yii::$app->request->post();
  85. $hasMap = dict::getDict('hasMap');
  86. if ($hasMap == 0) {
  87. util::fail('暂不支持跑腿功能');
  88. }
  89. $mainData = $this->main;
  90. $wxStoreId = $mainData->wxStoreId ?? '';
  91. if (empty($wxStoreId)) {
  92. util::fail('商家还没有开通跑腿');
  93. }
  94. $cargoName = $post['cargo_name']; // 商品名称
  95. $cargo = [
  96. 'cargo_name' => $cargoName, // 商品名称
  97. 'cargo_weight' => intval($post['weight'] * 1000), // 单位:克 -- 把千克转换为克 ---- 重量(用户未知)-- 大概
  98. 'cargo_price' => intval($post['price'] * 100), // 单位:分 -- 把元转换为分
  99. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  100. 'cargo_num' => intval($post['package_num'])
  101. ];
  102. $originalLng = doubleval($post['user_lng']);
  103. $originalLat = doubleval($post['user_lat']);
  104. $userName = !empty($post['user_name']) ? $post['user_name'] : '游客';
  105. $orderData = [
  106. 'wx_store_id' => $wxStoreId,
  107. 'user_name' => $userName,
  108. 'user_phone' => $post['user_phone'],
  109. 'user_lng' => $originalLng,
  110. 'user_lat' => $originalLat,
  111. 'user_address' => $post['user_address'],
  112. 'cargo' => $cargo,
  113. ];
  114. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  115. $result = IntraCityExpress::preAddOrder($orderData);
  116. if ($result['errcode'] === 0) {
  117. util::success($result, "查询成功");
  118. } else {
  119. Yii::error("运费查询失败:" . json_encode($result));
  120. $errMsg = $result['errmsg'] ?? '';
  121. $errCode = $result['errcode'] ?? '';
  122. noticeUtil::push("运费查询失败,原因:" . $errMsg . ",编号:" . $errCode, '15280215347');
  123. util::fail('运费查询失败,请确认是否超过20公斤,编号896');
  124. }
  125. }
  126. //计算运费,请搜索关键词calc_freight,二个方法要合一起 ssh 20221014
  127. public function actionFreight()
  128. {
  129. $get = Yii::$app->request->get();
  130. $shop = $this->shop;
  131. $shopLat = isset($shop->lat) ? $shop->lat : '';
  132. $shopLong = isset($shop->long) ? $shop->long : '';
  133. // 判断地图功能是否正常。0 表示地图定位不可用,全部经纬度数据失效
  134. if (dict::getDict('hasMap') == 0) {
  135. $shopLat = '';
  136. $shopLong = '';
  137. }
  138. if (empty($shopLat) || empty($shopLong)) {
  139. util::success([
  140. 'distance' => 0,
  141. 'showDistance' => 0,
  142. 'fee' => 0,
  143. 'hasMap' => dict::getDict('hasMap'),
  144. 'shop' => 'fail' //门店引起的失败
  145. ]);
  146. }
  147. $userLat = $get['lat'] ?? '';
  148. $userLong = $get['long'] ?? '';
  149. if (empty($userLat) || empty($userLong)) {
  150. util::success([
  151. 'distance' => 0,
  152. 'showDistance' => 0,
  153. 'fee' => 0,
  154. 'hasMap' => dict::getDict('hasMap'),
  155. 'client' => 'fail' //用户端定位失败
  156. ]);
  157. }
  158. $weight = $get['weight'] ?? 0;
  159. if (empty($weight)) {
  160. util::success([
  161. 'distance' => 0,
  162. 'showDistance' => 0,
  163. 'fee' => 0,
  164. 'hasMap' => dict::getDict('hasMap'),
  165. 'weight' => 'fail' //重量不对
  166. ]);
  167. }
  168. //data: {distance: "321", showDistance: "0.3", fee: "12.00"}
  169. $respond = OrderClass::getDistanceFee($userLat, $userLong, $shopLat, $shopLong, $weight);
  170. util::success($respond);
  171. }
  172. // 零售商的限购花材信息(与批发端 PurchaseController::actionLimitBuyInfo 对应,按花店客户与 hd_limit_buy Redis)
  173. public function actionLimitBuyInfo()
  174. {
  175. $post = Yii::$app->request->post();
  176. $list = $post['list'] ?? [];
  177. if (empty($list) || !is_array($list)) {
  178. util::fail('请选择花材');
  179. }
  180. $hd = $this->hd;
  181. if (empty($hd)) {
  182. util::fail('没有找到花店');
  183. }
  184. if ($hd->shopId != $this->shopId) {
  185. util::fail('不是你的花店');
  186. }
  187. $hdCustomId = $hd->customId ?? 0;
  188. if (empty($hdCustomId)) {
  189. util::fail('没有找到客户');
  190. }
  191. $respond = \bizHd\product\classes\ProductClass::getLimitBuyInfoByList($list, $hdCustomId);
  192. util::success($respond);
  193. }
  194. //购买花材 ssh 20220511
  195. public function actionBuyItem()
  196. {
  197. $post = Yii::$app->request->post();
  198. $post['sjId'] = $this->sjId;
  199. $post['shopId'] = $this->shopId;
  200. $post['payWay'] = 0;
  201. $post['mainId'] = $this->mainId ?? 0;
  202. $post['userId'] = $this->userId ?? 0;
  203. //避免重复提交
  204. $userId = $this->userId;
  205. util::checkRepeatCommit($userId, 3);
  206. $shop = $this->shop;
  207. $openShop = \bizHd\shop\classes\ShopClass::getOpenShop($shop);
  208. if ($openShop == 0) {
  209. util::fail('已休店');
  210. }
  211. //普莲花艺、叶上花、丰行、小武鲜花、九江云朵、源花汇、紫荆不能在花卉宝下单,多处要同步修改,关键词ls_mall_not_open
  212. $mainId = $this->mainId;
  213. if (getenv('YII_ENV') == 'production') {
  214. if (in_array($mainId, [40057, 7779, 42940, 26374, 10536, 65381])) {
  215. util::fail('暂时无法访问');
  216. }
  217. } else {
  218. if (in_array($mainId, [0, 1])) {
  219. util::fail('暂时无法访问');
  220. }
  221. }
  222. $hdId = $post['hdId'] ?? 0;
  223. $hd = HdClass::getById($hdId, true);
  224. if (empty($hd)) {
  225. util::fail('没有找到花店');
  226. }
  227. if ($hd->shopId != $this->shopId) {
  228. util::fail('不是你的花店');
  229. }
  230. $post['hdName'] = $hd->name ?? '';
  231. $hdCustomId = $hd->customId ?? 0;
  232. $custom = CustomClass::getById($hdCustomId, true);
  233. if (empty($custom)) {
  234. util::fail('没有找到客户');
  235. }
  236. $customName = $custom->name ?? '';
  237. $post['customId'] = $hdCustomId;
  238. $post['customName'] = $customName;
  239. $post['customNamePy'] = stringUtil::py($customName);
  240. $now = time();
  241. //订单30分钟后过期
  242. $expireTime = $now + 1800;
  243. $post['deadline'] = $expireTime;
  244. //商城
  245. $post['fromType'] = dict::getDict('fromType', 'mall');
  246. $productJson = $post['product'] ?? '';
  247. if (empty($productJson) && empty($groupId)) {
  248. util::fail('请选择商品');
  249. }
  250. $productList = json_decode($productJson, true);
  251. if (empty($productList)) {
  252. util::fail('请选择商品');
  253. }
  254. $ids = array_unique(array_filter(array_column($productList, 'productId')));
  255. $productInfoList = productClass::getByIds($ids, null, 'id');
  256. if (!empty($productInfoList)) {
  257. $presellData = [];
  258. $nowTime = strtotime(date("Y-m-d"));
  259. foreach ($productInfoList as $currentInfo) {
  260. if (!isset($currentInfo['mainId']) || $currentInfo['mainId'] != $this->mainId) {
  261. util::fail('只能选一家的商品,请清空重新选呢');
  262. }
  263. $presell = $currentInfo['presell'] ?? 0;
  264. $presellData[] = $presell;
  265. if ($presell == 1) {
  266. if (empty($post['reachDate'])) {
  267. util::fail('请选择配送或取货日期');
  268. }
  269. $sendTimeWant = $post['reachDate'];
  270. if (strtotime($sendTimeWant) < $nowTime) {
  271. util::fail('不能选择过去时间');
  272. }
  273. $hasDateStr = $currentInfo['presellDate'] ?? [];
  274. $hasDate = explode(',', trim($hasDateStr));
  275. if (empty($hasDate)) {
  276. util::fail('预售日期有问题,请提醒门店');
  277. }
  278. if (!in_array(strtotime($sendTimeWant), $hasDate)) {
  279. util::fail("有预售花材在{$sendTimeWant}没到货");
  280. }
  281. $post['presell'] = 1;
  282. }
  283. }
  284. if (count($productInfoList) != count($ids)) {
  285. util::fail('存在无效商品');
  286. }
  287. $presellData = array_unique($presellData);
  288. if (count($presellData) > 1) {
  289. util::fail('预售和非预售花材不能一起下单');
  290. }
  291. } else {
  292. util::fail('花材不存在');
  293. }
  294. $connection = Yii::$app->db;
  295. $transaction = $connection->beginTransaction();
  296. $transactionFinished = false;
  297. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  298. if ($transactionFinished) {
  299. return;
  300. }
  301. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  302. if ($transaction->isActive) {
  303. $transaction->rollBack();
  304. }
  305. });
  306. try {
  307. $orderValidTime = !getenv('ORDER_VALID_TIME') ? 600 : getenv('ORDER_VALID_TIME');
  308. $post['deadline'] = time() + $orderValidTime;
  309. $post['reachDate'] = !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  310. $post['needPrint'] = dict::getDict('needPrint', 'need');
  311. $user = $this->user;
  312. $post['bookMobile'] = $user->mobile ?? '';
  313. $post['bookName'] = $user->name ?? '';
  314. $hasPay = 0;
  315. $modifyPrice = 0;
  316. //各个等级对应的price addPrice字段
  317. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  318. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  319. $totalWeight = 0;
  320. $totalNum = 0;
  321. $totalReachDiscount = 0;
  322. foreach ($productList as $eleKey => $element) {
  323. $level = 0;
  324. $productId = $element['productId'];
  325. $product = $productInfoList[$productId];
  326. if (empty($product)) {
  327. util::fail('有商品信息没有找到');
  328. }
  329. $num = $element['num'] ?? 0; // 此次购买数量
  330. $limitKey = \bizHd\product\classes\ProductClass::LIMIT_BUY_KEY . $productId;
  331. $hasBuyNum = Yii::$app->redis->executeCommand('HGET', [$limitKey, $hdCustomId]);
  332. $hasBuyNum = $num + ($hasBuyNum == null ? 0 : $hasBuyNum); // 已购买总数量
  333. $price = \bizGhs\product\classes\ProductClass::getFinalPrice($product, $level, $priceMap, $addPriceMap, 0, $num, $hasBuyNum);
  334. $reachNum = $product['reachNum'] ?? 0;
  335. $reachNumDiscount = $product['reachNumDiscount'] ?? 0;
  336. if ($reachNum > 0 && $num >= $reachNum && $reachNumDiscount > 0) {
  337. $currentReachDiscount = bcmul($reachNumDiscount, $num, 2);
  338. $totalReachDiscount = bcadd($totalReachDiscount, $currentReachDiscount, 2);
  339. }
  340. $currentTotal = bcmul($price, $num, 2);
  341. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  342. $productList[$eleKey]['unitPrice'] = $price;
  343. $weight = $product['weight'] ?? 0;
  344. $currentWeight = bcmul($num, $weight, 2);
  345. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  346. $totalNum = bcadd($totalNum, $num);
  347. if ($product['limitBuy'] > 0) {
  348. $product['productId'] = $productId;
  349. \bizHd\product\classes\ProductClass::handleLimitBuy($product, $hdCustomId, floatval($num));
  350. }
  351. }
  352. $post['product'] = $productList;
  353. $post['reachDiscountPrice'] = $totalReachDiscount;
  354. //不能前端传运费过来,只能通过跑腿接口计算出来
  355. unset($post['sendCost']);
  356. $mapSet = ShopClass::hasIntraCity($this->shop);
  357. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  358. if (isset($post['sendType']) && $post['sendType'] == 2 && $openIntraCity != 0) {
  359. if ($openIntraCity == 2) {
  360. util::fail('不能使用跑腿');
  361. }
  362. $cargoName = '花材'; // 商品名称
  363. $cargo = [
  364. 'cargo_name' => $cargoName, // 商品名称
  365. 'cargo_weight' => intval($totalWeight * 1000), // 单位:克 -- 把千克转换为克 ---- 重量(用户未知)-- 大概
  366. 'cargo_price' => intval($modifyPrice * 100), // 单位:分 -- 把元转换为分
  367. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  368. 'cargo_num' => $totalNum
  369. ];
  370. $customName = $custom->name;
  371. $customMobile = $custom->mobile;
  372. if (empty($post['long']) || empty($post['lat'])) {
  373. util::fail('位置错误');
  374. }
  375. // $originalLng = doubleval($post['long']);
  376. // $originalLat = doubleval($post['lat']);
  377. // $city = $post['city'] ?? '';
  378. // $dist = $post['dist'] ?? '';
  379. // $address = $post['address'] ?? '';
  380. // $showAddress = $post['showAddress'] ?? '';
  381. // $userAddress = $city . $dist . $address . "({$showAddress})";
  382. // $main = $this->main;
  383. $shop = $this->shop;
  384. $shopLat = $shop->lat ?? '';
  385. $shopLong = $shop->long ?? '';
  386. if (empty($shopLat) || empty($shopLong)) {
  387. util::fail('商家门店地址定位未设置,编号263');
  388. }
  389. // $wxStoreId = $main->wxStoreId ?? 0;
  390. // if (empty($wxStoreId)) {
  391. // util::fail('商家还没有开通跑腿功能');
  392. // }
  393. // $orderData = [
  394. // 'wx_store_id' => $wxStoreId,
  395. // 'user_name' => $customName,
  396. // 'user_phone' => $customMobile,
  397. // 'user_lng' => $originalLng,
  398. // 'user_lat' => $originalLat,
  399. // 'user_address' => $userAddress,
  400. // 'cargo' => $cargo,
  401. // ];
  402. // //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  403. // $result = IntraCityExpress::preAddOrder($orderData);
  404. // $errCode = $result['errcode'] ?? 1;
  405. // if ($errCode != 0) {
  406. // $errMsg = $result['errmsg'] ?? '';
  407. // util::fail('获取运费错误:' . $errMsg);
  408. // }
  409. // $fee = $result['est_fee'] ?? 0;
  410. // $distance = $result['distance'] ?? 0;
  411. // $sendCost = bcdiv($fee, 100, 2);
  412. $distance = 0;
  413. $sendCost = 0;
  414. //生成随机订单号,不要跟原来的混起来,跑腿-销售单-
  415. $prefix = 'PT-XSD-' . $this->mainId . '-';
  416. $orderSn = $prefix . round(microtime(true) * 1000);
  417. $ghsInfo = ['mainId' => $this->mainId, 'shopId' => $this->shopId];
  418. // 这儿要调用跑腿接口计算运费和距离
  419. try {
  420. if (empty($post['deliveryPlatform'])) {
  421. util::fail('请选择跑腿');
  422. }
  423. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  424. 'productList' => $productList,
  425. 'deliveryPlatform' => $post['deliveryPlatform'],
  426. 'deliveryBracketContent' => $post['deliveryBracketContent'], // 平台多报价识别id
  427. 'ghsInfo' => $ghsInfo,
  428. 'custom' => $this->user, // $custom 数据有问题,要是 user
  429. 'order' => [
  430. 'orderSn' => $orderSn,
  431. 'goodsType' => 1, //商品类型:0花束 1花材
  432. 'itemTotalAmount' => $modifyPrice,
  433. 'remark' => $post['remark'] ?? '',
  434. ],
  435. 'mainId' => $this->mainId,
  436. 'productCount' => $totalNum,
  437. ]);
  438. $sendCost = $quoteResult['sendCost'];
  439. $distance = $quoteResult['sendDistance'];
  440. } catch (\Exception $e) {
  441. util::fail($e->getMessage());
  442. }
  443. $post['sendCost'] = $sendCost;
  444. $post['sendDistance'] = $distance;
  445. //noticeUtil::push("零售订单(花材),获取运费:{$sendCost} 重量:{$totalWeight} 距离:{$distance}m 姓名:{$customName} 手机号 {$customMobile} 金额:{$modifyPrice} 数量:{$totalNum}", '15280215347');
  446. $modifyPrice = bcadd($modifyPrice, $sendCost, 2);
  447. }
  448. //红包使用,多有处,关键词 use_hb_action
  449. $hbId = $post['hbId'] ?? 0;
  450. $hb = null;
  451. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  452. $hb = HbClass::getById($hbId, true);
  453. if (!empty($hb)) {
  454. if ($hb->customId != $hdCustomId) {
  455. util::fail('不是你的红包');
  456. }
  457. if ($hb->amount != $post['hbAmount']) {
  458. util::fail('红包金额不相等'); //红包数据可能被串改
  459. }
  460. if ($hb->status == 1) {
  461. util::fail('红包已使用');
  462. }
  463. if ($hb->status == -1) {
  464. util::fail('红包已作废');
  465. }
  466. if ($hb->endTime < time()) {
  467. $hb->status = -1;
  468. $hb->save();
  469. util::fail('红包已失效');
  470. }
  471. if ($hb->beginTime > time()) {
  472. util::fail('红包可使用期未到');
  473. }
  474. // 按适用范围计算适用商品合计是否达到最低消费
  475. HbScopeClass::assertMinConsume($hb, $productList ?? [], $modifyPrice);
  476. if ($this->shop->rechargeWeal == 3) {
  477. if (bccomp($custom->balance, $modifyPrice) == -1) {
  478. //不要限制提交
  479. //util::fail('此红包非余额支付不可用(您的余额不足)');
  480. }
  481. }
  482. $modifyPrice = bcsub($modifyPrice, $hb->amount, 2);//扣减红包
  483. } else {
  484. Yii::error('没有找到红包,hbId', $hbId . ' ' . __METHOD__);
  485. util::fail('红包无效');
  486. }
  487. }
  488. $post['bigNum'] = $totalNum;
  489. $post['modifyPrice'] = $modifyPrice;
  490. //多处调用这个方法,注意同步修改,搜索关键词 createHdNewOrder
  491. $return = \bizHd\order\services\OrderService::createHdOrder($post, $custom, $hasPay);
  492. if (!empty($hb)) {
  493. $hb->status = 1;
  494. $hb->orderId = $return->id;
  495. $hb->save();
  496. }
  497. if (isset($return->shopId)) {
  498. if ($return->shopId == 7610) {
  499. if ($return->actPrice < 200) {
  500. if ($return->sendType == 0) {
  501. util::fail('满200元支持送货上门');
  502. }
  503. }
  504. }
  505. }
  506. if ($return->sendType == 2) {
  507. $ext = ShopExtClass::getByCondition(['shopId' => $return->shopId], true, null, 'id,shopId,thirdSend');
  508. if ($ext->thirdSend == 1) {
  509. util::fail('本店暂不能使用跑腿呢');
  510. }
  511. }
  512. $transaction->commit();
  513. $transactionFinished = true;
  514. \bizHd\product\classes\ProductClass::clearLimitBuyRollbackSnapshot();
  515. $orderSn = $return->orderSn ?? '';
  516. $orderPrice = $return->orderPrice ?? 0;
  517. $id = $return->id ?? 0;
  518. $getPayType = dict::getDict('getPayType');
  519. util::success(['orderSn' => $orderSn, 'totalPrice' => $orderPrice, 'couponId' => 0, 'id' => $id, 'getPayType' => $getPayType]);
  520. } catch (\Exception $e) {
  521. $transaction->rollBack();
  522. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  523. $transactionFinished = true;
  524. Yii::error("失败原因:" . $e->getMessage());
  525. util::fail('下单失败');
  526. }
  527. }
  528. //商城下单操作 ssh 2019.12.3
  529. public function actionCreateOrder()
  530. {
  531. $post = Yii::$app->request->post();
  532. //避免重复提交
  533. $userId = $this->userId;
  534. util::checkRepeatCommit($userId, 3);
  535. $shop = $this->shop;
  536. $openShop = \bizHd\shop\classes\ShopClass::getOpenShop($shop);
  537. if ($openShop == 0) {
  538. util::fail('已休店');
  539. }
  540. $goodsId = $post['goodsId'] ?? 0;
  541. $specGoodsId = (int)($post['specGoodsId'] ?? 0);
  542. $goodsNum = isset($post['goodsNum']) && $post['goodsNum'] > 0 ? $post['goodsNum'] : 1;
  543. $sendType = $post['sendType'] ?? dict::getDict('sendType', 'thirdSend');
  544. if (empty($goodsId)) {
  545. util::fail('请选择商品');
  546. }
  547. $mainId = $this->mainId;
  548. $goodsInfo = GoodsClass::getById($goodsId, true);
  549. if (empty($goodsInfo)) {
  550. util::fail('没有找到商品');
  551. }
  552. if ($goodsInfo->mainId != $mainId) {
  553. util::fail('不是你的商品');
  554. }
  555. if ($specGoodsId > 0) {
  556. // 首规格落在主记录:specGoodsId 可以等于主商品 id,直接用主记录行售卖
  557. if ($specGoodsId != $goodsId) {
  558. $specGoods = GoodsClass::getById($specGoodsId, true);
  559. if (empty($specGoods) || $specGoods->mainId != $mainId || $specGoods->masterId != $goodsId || $specGoods->delStatus != 0 || $specGoods->status != 1) {
  560. util::fail('规格不可用');
  561. }
  562. $goodsInfo = $specGoods;
  563. }
  564. } elseif ((int)($goodsInfo->masterId ?? 0) === 0 && (int)($goodsInfo->goodsStyle ?? 0) === 1) {
  565. util::fail('请选择规格');
  566. }
  567. $stock = $goodsInfo->stock ?? 0;
  568. $saleGoodsId = $specGoodsId > 0 ? $specGoodsId : $goodsId;
  569. $activityType = strval($post['activityType'] ?? '');
  570. if (bccomp($goodsNum, floatval($stock), 2) > 0) {
  571. // 库存不足返回商品标识,供结算页红框高亮(与限购超限同形态)
  572. $this->failStockExceed([
  573. 'productId' => $saleGoodsId,
  574. 'goodsId' => $goodsId,
  575. 'specGoodsId' => $specGoodsId,
  576. 'property' => 0,
  577. 'activityType' => $activityType,
  578. 'stock' => $stock,
  579. 'num' => $goodsNum,
  580. ]);
  581. }
  582. //事务处理
  583. $connection = Yii::$app->db;
  584. $transaction = $connection->beginTransaction();
  585. $transactionFinished = false;
  586. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  587. if ($transactionFinished) {
  588. return;
  589. }
  590. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  591. if ($transaction->isActive) {
  592. $transaction->rollBack();
  593. }
  594. });
  595. try {
  596. $custom = $this->custom;
  597. if (empty($custom)) {
  598. util::fail('个人信息缺失');
  599. }
  600. $customId = $custom->id ?? 0;
  601. $hd = $this->hd;
  602. $post['customId'] = $customId;
  603. $customName = $custom->name ?? '';
  604. $post['customName'] = $customName;
  605. $post['customNamePy'] = stringUtil::py($customName);
  606. $post['hdId'] = $hd->id ?? 0;
  607. $post['hdName'] = $hd->name ?? '';
  608. $user = $this->user;
  609. $post['bookName'] = $user->name ?? '';
  610. $bookMobile = !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  611. $bookMobile = empty($bookMobile) && !empty($user->mobile) ? $user->mobile : $bookMobile;
  612. $post['bookMobile'] = $bookMobile;
  613. $post['payWay'] = 0;
  614. $shop = $this->shop;
  615. // 秒杀商品:不信任前端传的价格,独立回查秒杀配置核实活动状态/库存/限购后再核价
  616. $seckillRow = null;
  617. $seckillActivityGoodsId = 0;
  618. if ($activityType === 'seckill') {
  619. $seckillRow = HomePageModuleClass::getSeckillActiveRow($mainId, intval($this->shopId), $saleGoodsId);
  620. if (empty($seckillRow)) {
  621. util::fail('秒杀活动已结束或商品已下架,请重新选择');
  622. }
  623. $seckillActivityGoodsId = intval($seckillRow['id'] ?? ($seckillRow['activityGoodsId'] ?? 0));
  624. if ($seckillActivityGoodsId <= 0) {
  625. util::fail('秒杀商品版本无效,请重新选择');
  626. }
  627. $seckillStock = floatval($seckillRow['stock'] ?? 0);
  628. $soldCount = HomePageModuleClass::getSeckillSoldCount($mainId, $seckillActivityGoodsId);
  629. $seckillRemain = bcsub($seckillStock, $soldCount, 2);
  630. if (bccomp($seckillRemain, '0', 2) < 0) {
  631. $seckillRemain = '0';
  632. }
  633. if (bccomp($goodsNum, $seckillRemain, 2) > 0) {
  634. $this->failStockExceed([
  635. 'productId' => $saleGoodsId,
  636. 'goodsId' => $goodsId,
  637. 'specGoodsId' => $specGoodsId,
  638. 'property' => 0,
  639. 'activityType' => 'seckill',
  640. 'stock' => $seckillRemain,
  641. 'num' => $goodsNum,
  642. ]);
  643. }
  644. $seckillLimit = floatval($seckillRow['limit'] ?? 0);
  645. if ($seckillLimit > 0) {
  646. $boughtCount = HomePageModuleClass::getSeckillCustomBoughtCount($mainId, $seckillActivityGoodsId, $customId);
  647. if (bcadd($boughtCount, $goodsNum, 2) > $seckillLimit) {
  648. // 返回超限商品,供结算页红框高亮;code=-1 与花材限购错误对齐
  649. HomePageModuleClass::failSeckillLimitExceed($saleGoodsId, $goodsId, $specGoodsId, $seckillLimit, $boughtCount, $goodsNum);
  650. }
  651. }
  652. }
  653. if ($seckillRow) {
  654. $goodsInfo->priceType = 1;
  655. $unitPrice = floatval($seckillRow['price'] ?? 0);
  656. if ($unitPrice <= 0) {
  657. util::fail('秒杀价格异常,不能下单');
  658. }
  659. // 通过校验后立即预占名额,失败/异常时随事务一起回滚(见 register_shutdown_function)
  660. HomePageModuleClass::reserveSeckillPurchase($mainId, $seckillActivityGoodsId, $customId, $goodsNum);
  661. } else {
  662. $params = [];
  663. $goodsData = $goodsInfo->attributes;
  664. $ret = \bizHd\goods\classes\GoodsClass::getFinalPrice($goodsData, $shop, $custom, $params);
  665. $goodsInfo->priceType = $ret['priceType'] ?? 0;
  666. if ($goodsInfo->priceType == 0) {
  667. util::fail('没有价格,不能下单哈');
  668. }
  669. $unitPrice = $ret['price'] ?? 0;
  670. if ($unitPrice <= 0) {
  671. util::fail('没有价格,不能下单呢');
  672. }
  673. }
  674. //计算总金额
  675. $goodsPrice = $unitPrice * $goodsNum;
  676. //计算运费
  677. $sendDistance = 0;
  678. $sendCost = 0;
  679. if ($sendType == dict::getDict('sendType', 'thirdSend')) {
  680. $receiveUserName = $post['receiveUserName'] ?? '';
  681. if (empty($receiveUserName)) {
  682. util::fail('请填写收花人名字');
  683. }
  684. $receiveMobile = $post['receiveMobile'] ?? '';
  685. if (empty($receiveMobile)) {
  686. util::fail('请填写收花人手机号');
  687. }
  688. if (!stringUtil::isMobile($receiveMobile)) {
  689. util::fail('收花人手机号错误');
  690. }
  691. }
  692. $mapSet = ShopClass::hasIntraCity($shop);
  693. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  694. if ($sendType == dict::getDict('sendType', 'thirdSend') && $openIntraCity != 0) {
  695. if ($openIntraCity == 2) {
  696. util::fail('不能使用跑腿');
  697. }
  698. $cutomInfo = [
  699. 'name' => $post['receiveUserName'],
  700. 'mobile' => $post['receiveMobile'],
  701. 'fullAddress' => $post['address'],
  702. 'floor' => $post['floor'],
  703. 'dist' => $post[''] ?? '',
  704. 'lat' => $post['lat'],
  705. 'long' => $post['long'],
  706. 'address' => $post['address'],
  707. 'city' => $post['city'],
  708. ];
  709. $cutomInfo = (object)$cutomInfo;
  710. // 生成随机花束订单号
  711. $prefix = 'KD_CS-' . $this->mainId . '-';
  712. $orderSn = $prefix . round(microtime(true) * 1000);
  713. // 使用 DeliveryQuoteUtil 获取配送报价
  714. try {
  715. if ($goodsInfo->weight > 5) {
  716. $goodsInfo->weight = 5;
  717. }
  718. if (empty($post['deliveryPlatform'])) {
  719. util::fail('请选择跑腿');
  720. }
  721. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  722. 'productList' => [['bigNum' => $goodsNum, 'weight' => $goodsInfo->weight]],
  723. 'deliveryPlatform' => $post['deliveryPlatform'],
  724. 'deliveryBracketContent' => $post['deliveryBracketContent'], // 平台多报价识别id
  725. 'ghsInfo' => ['mainId' => $mainId, 'shopId' => $this->shopId],
  726. 'custom' => $cutomInfo,
  727. 'order' => [
  728. 'orderSn' => $orderSn,
  729. 'goodsType' => 0, //商品类型:0花束 1花材
  730. 'itemTotalAmount' => $goodsPrice,
  731. 'remark' => $post['remark'] ?? '',
  732. 'freightType' => $goodsInfo->freightType,
  733. ],
  734. 'mainId' => $this->mainId,
  735. 'productCount' => $goodsNum,
  736. ]);
  737. $sendCost = $quoteResult['sendCost'];
  738. $sendDistance = $quoteResult['sendDistance'];
  739. noticeUtil::push("零售订单(花束),获取运费:{$sendCost} 重量:{$goodsInfo->weight} 距离:{$sendDistance}m 姓名:{$customName} 金额:{$goodsPrice} 数量:{$goodsNum}");
  740. } catch (\Exception $e) {
  741. util::fail($e->getMessage());
  742. }
  743. }
  744. $post['sendDistance'] = $sendDistance;
  745. $post['sendCost'] = $sendCost;
  746. $post['sjId'] = $this->sjId;
  747. $post['shopId'] = $this->shopId;
  748. $post['mainId'] = $mainId;
  749. $post['userId'] = $this->userId;
  750. if ($goodsInfo->priceType == 0) {
  751. util::fail('没有价格,不能下单');
  752. }
  753. $modifyPrice = stringUtil::calcAdd($sendCost, $goodsPrice);
  754. //非门店订单
  755. $post['store'] = 0;
  756. //红包使用,多有处,关键词 use_hb_action
  757. $hbId = $post['hbId'] ?? 0;
  758. $hb = null;
  759. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  760. $hb = HbClass::getById($hbId, true);
  761. if (!empty($hb)) {
  762. if ($hb->customId != $customId) {
  763. util::fail('不是你的红包');
  764. }
  765. if ($hb->amount != $post['hbAmount']) {
  766. util::fail('红包金额不相等'); //红包数据可能被串改
  767. }
  768. if ($hb->status == 1) {
  769. util::fail('红包已使用');
  770. }
  771. if ($hb->status == -1) {
  772. util::fail('红包已作废');
  773. }
  774. if ($hb->endTime < time()) {
  775. $hb->status = -1;
  776. $hb->save();
  777. util::fail('红包已失效');
  778. }
  779. if ($hb->beginTime > time()) {
  780. util::fail('红包可使用期未到');
  781. }
  782. // 单花束下单:按适用范围校验最低消费
  783. $hbGoods = [[
  784. 'productId' => $goodsInfo->id ?? 0,
  785. 'goodsId' => $goodsInfo->id ?? 0,
  786. 'unitPrice' => $goodsPrice ?? 0,
  787. 'num' => $goodsNum ?? 1,
  788. 'linePrice' => $goodsPrice ?? 0,
  789. ]];
  790. HbScopeClass::assertMinConsume($hb, $hbGoods, $modifyPrice);
  791. if ($this->shop->rechargeWeal == 3) {
  792. if ($custom->balance < $modifyPrice) {
  793. util::fail('此红包非余额支付不可用(您的余额不足)');
  794. }
  795. }
  796. $modifyPrice = bcsub($modifyPrice, $hb->amount, 2);//扣减红包
  797. } else {
  798. Yii::error('没有找到红包,hbId', $hbId . ' ' . __METHOD__);
  799. util::fail('红包无效');
  800. }
  801. }
  802. $post['modifyPrice'] = $modifyPrice;
  803. //非自取订单考虑配送时间
  804. $post['reachDate'] = !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  805. $sendType = $post['sendType'] ?? 0;
  806. if ($sendType != 1) {
  807. if (empty($post['reachPeriod'])) {
  808. util::fail('请选择配送时间哈');
  809. }
  810. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  811. }
  812. $now = time();
  813. $expireTime = $now + 1800;//订单30分钟后过期
  814. $post['deadline'] = $expireTime;
  815. $orderSn = orderSn::getOrderSn();
  816. $post['orderSn'] = $orderSn;
  817. $post['fromType'] = dict::getDict('fromType', 'mall');
  818. $post['cash'] = 0;
  819. $post['mainId'] = $mainId;
  820. $post['needPrint'] = dict::getDict('needPrint', 'need');
  821. $hasPay = 0;
  822. $product = [['productId' => $saleGoodsId, 'unitType' => 0, 'property' => 0, 'unitPrice' => $unitPrice, 'num' => $goodsNum, 'seckillGoodsId' => $seckillActivityGoodsId]];
  823. $post['product'] = $product;
  824. $post['hasSeckill'] = $seckillRow ? 1 : 0;
  825. $return = \bizHd\order\services\OrderService::createHdOrder($post, $custom, $hasPay);
  826. //红包保存订单id
  827. if (!empty($hb)) {
  828. $hb->status = 1;
  829. $hb->orderId = $return->id;
  830. $hb->save();
  831. }
  832. $orderId = $return->id;
  833. $orderSn = $return->orderSn;
  834. $actPrice = $return->actPrice ?? 0;
  835. $transaction->commit();
  836. $transactionFinished = true;
  837. HomePageModuleClass::clearSeckillReservationSnapshot();
  838. util::success(['orderSn' => $orderSn, 'totalPrice' => $actPrice, 'couponId' => 0, 'id' => $orderId]);
  839. } catch (Exception $e) {
  840. $transaction->rollBack();
  841. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  842. $transactionFinished = true;
  843. Yii::info("失败原因:" . $e->getMessage());
  844. util::fail('下单失败');
  845. }
  846. }
  847. /**
  848. * 花束+花材合并结算下单
  849. * 复用 OrderService::createHdOrder,不改动 buy-item / create-order
  850. * 整单优惠:会员折扣与门店满减互斥,只落地优惠金额更大的一项(相等用会员折扣)
  851. * 秒杀商品已是活动价:seckillGoodsPrice 不计入会员折、门店满减金额基数,seckillGoodsNum 不计入满减件数门槛,仍计入应付和最低消费数量
  852. * 跑腿费(runnerSendCost)不参与会员折/门店满减基数,折后原额计入应付
  853. * 红包只抵商品金额:在加跑腿费/运费/包装费之前抵扣,抵扣额不超过商品合计,不抵运费
  854. */
  855. public function actionCreateMixOrder()
  856. {
  857. $post = Yii::$app->request->post();
  858. $post['sjId'] = $this->sjId;
  859. $post['shopId'] = $this->shopId;
  860. $post['payWay'] = 0;
  861. $post['mainId'] = $this->mainId ?? 0;
  862. $post['userId'] = $this->userId ?? 0;
  863. $userId = $this->userId;
  864. util::checkRepeatCommit($userId, 3);
  865. $mainId = $this->mainId;
  866. $shop = $this->shop;
  867. $openShop = \bizHd\shop\classes\ShopClass::getOpenShop($shop);
  868. if ($openShop == 0) {
  869. util::fail('已休店');
  870. }
  871. $hdId = $post['hdId'] ?? 0;
  872. $hd = HdClass::getById($hdId, true);
  873. if (empty($hd)) {
  874. util::fail('没有找到花店');
  875. }
  876. if ($hd->shopId != $this->shopId) {
  877. util::fail('不是你的花店');
  878. }
  879. $post['hdName'] = $hd->name ?? '';
  880. // 合并结算沿用花材购物车的客户身份(花店客户)
  881. $hdCustomId = $hd->customId ?? 0;
  882. $custom = CustomClass::getById($hdCustomId, true);
  883. if (empty($custom)) {
  884. util::fail('没有找到客户');
  885. }
  886. $customName = $custom->name;
  887. $post['customId'] = $hdCustomId;
  888. $post['customName'] = $customName;
  889. $post['customNamePy'] = stringUtil::py($customName);
  890. $productJson = $post['product'];
  891. if (empty($productJson)) {
  892. util::fail('请选择商品');
  893. }
  894. $productList = json_decode($productJson, true);
  895. if (empty($productList) || !is_array($productList)) {
  896. util::fail('请选择商品');
  897. }
  898. $itemRows = []; // 所有花材
  899. $goodsRows = []; // 所有花束
  900. foreach ($productList as $idx => $row) {
  901. $property = intval($row['property'] ?? -1);
  902. if ($property === 1) {
  903. $itemRows[$idx] = $row;
  904. } elseif ($property === 0) {
  905. if (strval($row['activityType'] ?? '') === 'groupBuy') {
  906. util::fail('团购商品请从开团页提交订单');
  907. }
  908. $goodsRows[$idx] = $row;
  909. } else {
  910. util::fail('商品类型错误');
  911. }
  912. }
  913. if (empty($itemRows) && empty($goodsRows)) {
  914. util::fail('请选择商品');
  915. }
  916. // ---- 花材校验与定价 ----
  917. $productInfoList = [];
  918. if (!empty($itemRows)) {
  919. $ids = array_unique(array_filter(array_map(function ($r) {
  920. return intval($r['productId'] ?? 0);
  921. }, $itemRows)));
  922. $productInfoList = ProductClass::getByIds($ids, null, 'id');
  923. if (empty($productInfoList)) {
  924. util::fail('花材不存在');
  925. }
  926. $presellData = [];
  927. $nowTime = strtotime(date("Y-m-d"));
  928. foreach ($productInfoList as $currentInfo) {
  929. if (!isset($currentInfo['mainId']) || $currentInfo['mainId'] != $this->mainId) {
  930. util::fail('只能选一家的商品,请清空重新选呢');
  931. }
  932. $presell = $currentInfo['presell'] ?? 0;
  933. $presellData[] = $presell;
  934. if ($presell == 1) {
  935. if (empty($post['reachDate'])) {
  936. util::fail('请选择配送或取货日期');
  937. }
  938. $sendTimeWant = $post['reachDate'];
  939. if (strtotime($sendTimeWant) < $nowTime) {
  940. util::fail('不能选择过去时间');
  941. }
  942. $hasDateStr = $currentInfo['presellDate'] ?? [];
  943. $hasDate = explode(',', trim($hasDateStr));
  944. if (empty($hasDate)) {
  945. util::fail('预售日期有问题,请提醒门店');
  946. }
  947. if (!in_array(strtotime($sendTimeWant), $hasDate)) {
  948. util::fail("有预售花材在{$sendTimeWant}没到货");
  949. }
  950. $post['presell'] = 1;
  951. }
  952. }
  953. if (count($productInfoList) != count($ids)) {
  954. util::fail('存在无效花材');
  955. }
  956. $presellData = array_unique($presellData);
  957. if (count($presellData) > 1) {
  958. util::fail('预售和非预售花材不能一起下单');
  959. }
  960. }
  961. $connection = Yii::$app->db;
  962. $transaction = $connection->beginTransaction();
  963. $transactionFinished = false;
  964. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  965. if ($transactionFinished) {
  966. return;
  967. }
  968. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  969. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  970. if ($transaction->isActive) {
  971. $transaction->rollBack();
  972. }
  973. });
  974. try {
  975. $orderValidTime = !getenv('ORDER_VALID_TIME') ? 600 : getenv('ORDER_VALID_TIME'); // TODO 找少华确认 -- 测试环境是 600
  976. $post['deadline'] = time() + $orderValidTime;
  977. $post['reachDate'] = !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  978. $post['needPrint'] = dict::getDict('needPrint', 'need');
  979. $post['fromType'] = dict::getDict('fromType', 'mall');
  980. $post['store'] = 0;
  981. $user = $this->user;
  982. $post['bookMobile'] = $user->mobile ?? '';
  983. $post['bookName'] = $user->name ?? '';
  984. $hasPay = 0;
  985. $modifyPrice = 0;
  986. $totalWeight = 0;
  987. $totalNum = 0;
  988. $itemBigNum = 0;
  989. $totalReachDiscount = 0;
  990. $resolvedProduct = [];
  991. $hasSeckillGoods = false;
  992. // 秒杀商品行合计:供会员折/门店满减剔除,避免活动价再叠整单优惠
  993. $seckillGoodsPrice = 0;
  994. // 秒杀花束份数:不计入门店满减件数门槛,最低消费数量仍按整单份数
  995. $seckillGoodsNum = 0;
  996. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  997. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  998. $post['orderType'] = 0;
  999. foreach ($productList as $eleKey => $element) {
  1000. $property = $element['property']; // 1: 花材, 0: 花束
  1001. if ($property === 1) { // 花材
  1002. $level = 0;
  1003. $productId = $element['productId'];
  1004. $product = $productInfoList[$productId] ?? null;
  1005. if (empty($product)) {
  1006. util::fail('有花材信息没有找到');
  1007. }
  1008. $num = $element['num'] ?? 0;
  1009. $itemStock = floatval($product['stock'] ?? 0);
  1010. if (bccomp(floatval($num), $itemStock, 2) > 0) {
  1011. // 花材库存不足也返回 productId,确认页/购物车按限购同款红框提示超出量
  1012. $this->failStockExceed([
  1013. 'productId' => $productId,
  1014. 'goodsId' => 0,
  1015. 'specGoodsId' => 0,
  1016. 'property' => 1,
  1017. 'activityType' => '',
  1018. 'stock' => $itemStock,
  1019. 'num' => $num,
  1020. ]);
  1021. }
  1022. $limitKey = \bizHd\product\classes\ProductClass::LIMIT_BUY_KEY . $productId;
  1023. $hasBuyNum = Yii::$app->redis->executeCommand('HGET', [$limitKey, $hdCustomId]);
  1024. $hasBuyNum = $num + ($hasBuyNum == null ? 0 : $hasBuyNum);
  1025. $price = \bizGhs\product\classes\ProductClass::getFinalPrice($product, $level, $priceMap, $addPriceMap, 0, $num, $hasBuyNum);
  1026. $reachNum = $product['reachNum'] ?? 0;
  1027. $reachNumDiscount = $product['reachNumDiscount'] ?? 0;
  1028. if ($reachNum > 0 && $num >= $reachNum && $reachNumDiscount > 0) {
  1029. $currentReachDiscount = bcmul($reachNumDiscount, $num, 2);
  1030. $totalReachDiscount = bcadd($totalReachDiscount, $currentReachDiscount, 2);
  1031. }
  1032. $currentTotal = bcmul($price, $num, 2);
  1033. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  1034. $weight = $product['weight'] ?? 0;
  1035. $currentWeight = bcmul($num, $weight, 2);
  1036. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  1037. $totalNum = bcadd($totalNum, $num);
  1038. $itemBigNum = bcadd($itemBigNum, $num);
  1039. if (($product['limitBuy'] ?? 0) > 0) {
  1040. $product['productId'] = $productId;
  1041. \bizHd\product\classes\ProductClass::handleLimitBuy($product, $hdCustomId, floatval($num));
  1042. }
  1043. $resolvedProduct[] = [
  1044. 'productId' => $productId,
  1045. 'num' => $num,
  1046. 'itemId' => $element['itemId'] ?? 0,
  1047. 'unitType' => $element['unitType'] ?? 0,
  1048. 'property' => 1,
  1049. 'unitPrice' => $price,
  1050. ];
  1051. } else if ($property === 0) { // 花束
  1052. $goodsId = $element['goodsId']; // 主商品ID
  1053. $specGoodsId = $element['specGoodsId']; // 规格ID
  1054. $saleGoodsId = $element['productId']; // 记录用于销售的商品ID,通常为具体的规格或产品ID
  1055. $goodsNum = isset($element['num']) && $element['num'] > 0 ? $element['num'] : 1;
  1056. if ($goodsId <= 0 && $saleGoodsId > 0) {
  1057. $probe = GoodsClass::getById($saleGoodsId, true);
  1058. if (!empty($probe)) {
  1059. $masterId = intval($probe->masterId);
  1060. if ($masterId > 0) {
  1061. $goodsId = $masterId;
  1062. $specGoodsId = $saleGoodsId;
  1063. } else {
  1064. $goodsId = $saleGoodsId;
  1065. }
  1066. }
  1067. }
  1068. if ($goodsId <= 0) {
  1069. util::fail('请选择花束商品');
  1070. }
  1071. $goodsInfo = GoodsClass::getById($goodsId, true);
  1072. if (empty($goodsInfo)) {
  1073. util::fail('没有找到花束商品');
  1074. }
  1075. if ($goodsInfo->mainId != $mainId) {
  1076. util::fail('不是你的商品');
  1077. }
  1078. if ($specGoodsId > 0) {
  1079. // 首规格落在主记录:specGoodsId 可以等于主商品 id,直接用主记录行售卖
  1080. if ($specGoodsId != $goodsId) {
  1081. $specGoods = GoodsClass::getById($specGoodsId, true);
  1082. if (empty($specGoods) || $specGoods->mainId != $mainId || $specGoods->masterId != $goodsId || $specGoods->delStatus != 0 || $specGoods->status != 1) {
  1083. util::fail('规格不可用');
  1084. }
  1085. $goodsInfo = $specGoods;
  1086. $saleGoodsId = $specGoodsId;
  1087. } else {
  1088. $saleGoodsId = $goodsId;
  1089. }
  1090. } else {
  1091. if ((int)($goodsInfo->masterId ?? 0) === 0 && (int)($goodsInfo->goodsStyle ?? 0) === 1) {
  1092. util::fail('请选择规格');
  1093. }
  1094. $saleGoodsId = $goodsId;
  1095. }
  1096. $stock = $goodsInfo->stock;
  1097. $stockSet = $goodsInfo->stockSet;
  1098. if ($stockSet == 1 && bccomp($goodsNum, floatval($stock), 2) > 0) {
  1099. $this->failStockExceed([
  1100. 'productId' => $saleGoodsId,
  1101. 'goodsId' => $goodsId,
  1102. 'specGoodsId' => $specGoodsId,
  1103. 'property' => 0,
  1104. 'activityType' => strval($element['activityType'] ?? ''),
  1105. 'stock' => $stock,
  1106. 'num' => $goodsNum,
  1107. ]);
  1108. }
  1109. // 秒杀商品:不信任前端传的价格,独立回查秒杀配置核实活动状态/库存/限购后再核价
  1110. $seckillRow = null;
  1111. $seckillActivityGoodsId = 0;
  1112. if (strval($element['activityType'] ?? '') === 'seckill') {
  1113. $seckillRow = HomePageModuleClass::getSeckillActiveRow($mainId, intval($this->shopId), $saleGoodsId);
  1114. if (empty($seckillRow)) {
  1115. util::fail('秒杀活动已结束或商品已下架,请重新选择');
  1116. }
  1117. $seckillActivityGoodsId = intval($seckillRow['id'] ?? ($seckillRow['activityGoodsId'] ?? 0));
  1118. if ($seckillActivityGoodsId <= 0) {
  1119. util::fail('秒杀商品版本无效,请重新选择');
  1120. }
  1121. $seckillStock = floatval($seckillRow['stock']);
  1122. $soldCount = HomePageModuleClass::getSeckillSoldCount($mainId, $seckillActivityGoodsId);
  1123. $seckillRemain = bcsub($seckillStock, $soldCount, 2);
  1124. if (bccomp($seckillRemain, '0', 2) < 0) {
  1125. $seckillRemain = '0';
  1126. }
  1127. if (bccomp($goodsNum, $seckillRemain, 2) > 0) {
  1128. $this->failStockExceed([
  1129. 'productId' => $saleGoodsId,
  1130. 'goodsId' => $goodsId,
  1131. 'specGoodsId' => $specGoodsId,
  1132. 'property' => 0,
  1133. 'activityType' => 'seckill',
  1134. 'stock' => $seckillRemain,
  1135. 'num' => $goodsNum,
  1136. ]);
  1137. }
  1138. $seckillLimit = floatval($seckillRow['limit'] ?? 0);
  1139. if ($seckillLimit > 0) {
  1140. $boughtCount = HomePageModuleClass::getSeckillCustomBoughtCount($mainId, $seckillActivityGoodsId, $hdCustomId); // TODO 同一个商品,如果缓存没有合理清除,就会一直限购
  1141. if (bcadd($boughtCount, $goodsNum, 2) > $seckillLimit) {
  1142. // 返回超限商品,供混合结算页/购物车红框高亮;code=-1 与花材限购错误对齐
  1143. HomePageModuleClass::failSeckillLimitExceed($saleGoodsId, $goodsId, $specGoodsId, $seckillLimit, $boughtCount, $goodsNum);
  1144. }
  1145. }
  1146. }
  1147. $goodsData = $goodsInfo->attributes;
  1148. if ($seckillRow) {
  1149. $unitPrice = floatval($seckillRow['price'] ?? 0);
  1150. if ($unitPrice <= 0) {
  1151. util::fail('秒杀价格异常,不能下单');
  1152. }
  1153. } else {
  1154. $ret = \bizHd\goods\classes\GoodsClass::getFinalPrice($goodsData, $shop, $custom, []);
  1155. $priceType = $ret['priceType'] ?? 0;
  1156. if ($priceType == 0) {
  1157. util::fail('花束没有价格,不能下单');
  1158. }
  1159. $unitPrice = $ret['price'] ?? 0;
  1160. if ($unitPrice <= 0) {
  1161. util::fail('花束没有价格,不能下单');
  1162. }
  1163. }
  1164. if ($seckillRow) {
  1165. // 通过校验后立即预占名额,失败/异常时随事务一起回滚(见 register_shutdown_function)
  1166. HomePageModuleClass::reserveSeckillPurchase($mainId, $seckillActivityGoodsId, $hdCustomId, $goodsNum);
  1167. $hasSeckillGoods = true;
  1168. }
  1169. $currentTotal = bcmul($unitPrice, $goodsNum, 2);
  1170. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  1171. if ($seckillRow) {
  1172. $seckillGoodsPrice = bcadd($seckillGoodsPrice, $currentTotal, 2);
  1173. $seckillGoodsNum = bcadd($seckillGoodsNum, $goodsNum, 2);
  1174. }
  1175. $weight = $goodsInfo->weight ?? 0;
  1176. if ($weight > 5) {
  1177. $weight = 5;
  1178. }
  1179. $currentWeight = bcmul($weight, $goodsNum, 2);
  1180. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  1181. $totalNum = bcadd($totalNum, $goodsNum);
  1182. $resolvedProduct[] = [
  1183. 'productId' => $saleGoodsId,
  1184. 'unitType' => 0,
  1185. 'property' => 0,
  1186. // 花束是否包运费:供跑腿运费分支判断(1=包运费)
  1187. 'freightType' => (int)($goodsInfo->freightType ?? 0),
  1188. 'unitPrice' => $unitPrice,
  1189. 'num' => $goodsNum,
  1190. 'seckillGoodsId' => $seckillActivityGoodsId,
  1191. ];
  1192. } else {
  1193. util::fail('商品类型错误');
  1194. }
  1195. }
  1196. // 根据 $resolvedProduct 设置订单类型:1纯花束 2纯花材 3混合
  1197. $properties = array_unique(array_column($resolvedProduct, 'property'));
  1198. if (count($properties) === 1) {
  1199. $post['orderType'] = intval($properties[0]) === 0 ? 1 : 2;
  1200. } elseif (count($properties) > 1) {
  1201. $post['orderType'] = 3;
  1202. }
  1203. $post['product'] = $resolvedProduct;
  1204. $post['reachDiscountPrice'] = $totalReachDiscount;
  1205. $goodsOnlyPrice = $modifyPrice;
  1206. unset($post['sendCost'], $post['packCost'], $post['packingFee'], $post['unMeetSendCost']);
  1207. $sendType = intval($post['sendType'] ?? 0);
  1208. $customInfo = \bizHd\order\classes\PsMethodClass::buildCustomInfo($hd, $custom);
  1209. // 最低消费数量:花材扎数 + 花束份数(与结算页「还差 N 扎」同源)
  1210. $unMeetBigNum = $itemBigNum;
  1211. foreach ($resolvedProduct as $row) {
  1212. if ((int)($row['property'] ?? 1) === 0) {
  1213. $unMeetBigNum = bcadd($unMeetBigNum, $row['num'] ?? 0, 2);
  1214. }
  1215. }
  1216. $additionalCosts = \bizHd\order\classes\PsMethodClass::calcFeeForMallContext(
  1217. $this->shopId,
  1218. $this->mainId,
  1219. $sendType,
  1220. $goodsOnlyPrice,
  1221. $unMeetBigNum,
  1222. $hdCustomId,
  1223. $customInfo
  1224. );
  1225. $unMeetSendCost = $additionalCosts['sendCost'] ?? 0;
  1226. $packingFee = $additionalCosts['packCost'] ?? 0;
  1227. $mapSet = ShopClass::hasIntraCity($this->shop);
  1228. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  1229. $hasItem = !empty($itemRows);
  1230. // 含花材(含混合)按花材报价 goodsType=1;纯花束按 0
  1231. $quoteGoodsType = $hasItem ? 1 : 0;
  1232. // 红包(归属花店客户,与 buy-item 一致)
  1233. // 红包只抵商品金额:在加跑腿费/运费/包装费之前抵扣,抵扣额不超过商品合计,避免红包抵用运费
  1234. $hbId = $post['hbId'] ?? 0;
  1235. $hb = null;
  1236. if ($hbId > 0) {
  1237. $hb = HbClass::getById($hbId, true);
  1238. if (!empty($hb)) {
  1239. if ($hb->customId != $hdCustomId) {
  1240. util::fail('不是你的红包');
  1241. }
  1242. if ($hb->amount != $post['hbAmount']) {
  1243. util::fail('红包金额不相等');
  1244. }
  1245. if ($hb->status == 1) {
  1246. util::fail('红包已使用');
  1247. }
  1248. if ($hb->status == -1) {
  1249. util::fail('红包已作废');
  1250. }
  1251. if ($hb->endTime < time()) {
  1252. $hb->status = -1;
  1253. $hb->save();
  1254. util::fail('红包已失效');
  1255. }
  1256. if ($hb->beginTime > time()) {
  1257. util::fail('红包可使用期未到');
  1258. }
  1259. // 混合结算:按适用范围用商品明细校验最低消费(不含运费包装费)
  1260. HbScopeClass::assertMinConsume($hb, $resolvedProduct ?? [], $goodsOnlyPrice ?? $modifyPrice);
  1261. // 此时 $modifyPrice 仍为纯商品合计,红包抵扣额以其为上限
  1262. $hbDeduct = $hb->amount;
  1263. if (bccomp($hbDeduct, $modifyPrice, 2) > 0) {
  1264. $hbDeduct = $modifyPrice;
  1265. }
  1266. $modifyPrice = bcsub($modifyPrice, $hbDeduct, 2);
  1267. // 回写实际抵扣额:createHdOrder 以此核算原价 prePrice 与优惠额,保持口径一致
  1268. $post['hbAmount'] = $hbDeduct;
  1269. } else {
  1270. util::fail('红包无效');
  1271. }
  1272. }
  1273. // 跑腿费(sendType=2 实际收取部分):不参与会员折/门店满减基数,随单传给折扣落地层剔除
  1274. $runnerSendCost = 0;
  1275. // 跑腿 style=2:与团购开团/参团共用 PsMethodClass::calcMixRunnerFreight
  1276. if (isset($post['sendType']) && (int)$post['sendType'] === 2) {
  1277. $runnerResult = PsMethodClass::calcMixRunnerFreight(
  1278. $shop,
  1279. $this->shopId,
  1280. $this->mainId,
  1281. $post,
  1282. $resolvedProduct,
  1283. $itemBigNum,
  1284. $goodsOnlyPrice,
  1285. $openIntraCity,
  1286. $quoteGoodsType,
  1287. $totalNum,
  1288. 'PT-MIX-',
  1289. '混合单'
  1290. );
  1291. $sendCost = $runnerResult['sendCost'];
  1292. $post['sendCost'] = $sendCost;
  1293. $post['sendDistance'] = $runnerResult['sendDistance'];
  1294. $post['freightSource'] = $runnerResult['freightSource'];
  1295. $modifyPrice = bcadd($modifyPrice, $sendCost, 2);
  1296. $runnerSendCost = $sendCost;
  1297. }
  1298. if ($unMeetSendCost > 0) {
  1299. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $unMeetSendCost, 2);
  1300. $modifyPrice = bcadd($modifyPrice, $unMeetSendCost, 2);
  1301. }
  1302. if ($packingFee > 0) {
  1303. $post['packingFee'] = $packingFee;
  1304. $modifyPrice = bcadd($modifyPrice, $packingFee, 2);
  1305. }
  1306. $psMethodError = \bizHd\order\classes\PsMethodClass::checkLimit(
  1307. $this->shopId,
  1308. $this->mainId,
  1309. $sendType,
  1310. $goodsOnlyPrice,
  1311. $unMeetBigNum,
  1312. $packingFee,
  1313. $unMeetSendCost,
  1314. $hdCustomId,
  1315. $customInfo
  1316. );
  1317. if ($psMethodError !== '') {
  1318. util::fail($psMethodError);
  1319. }
  1320. // 商家配送(0)/跑腿(2)必填配送时间;到店自取(1)、物流(3)、快递(4)不强制(后两者由客服确认时效)
  1321. $sendType = intval($post['sendType'] ?? 0);
  1322. if (in_array($sendType, [0, 2], true)) {
  1323. if (empty($post['reachPeriod'])) {
  1324. util::fail('请选择配送时间哈');
  1325. }
  1326. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  1327. } elseif (!empty($post['reachPeriod'])) {
  1328. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  1329. }
  1330. $post['bigNum'] = $totalNum;
  1331. $post['modifyPrice'] = $modifyPrice;
  1332. $post['hasSeckill'] = $hasSeckillGoods ? 1 : 0;
  1333. $post['seckillGoodsPrice'] = $seckillGoodsPrice;
  1334. $post['seckillGoodsNum'] = $seckillGoodsNum;
  1335. // 跑腿费随单传给折扣落地层(createHdOrder 会员折 / addOrder 门店满减),从可折扣基数剔除
  1336. $post['runnerSendCost'] = $runnerSendCost;
  1337. // 互斥比较与落单使用同一口径:秒杀活动价、跑腿费不参与会员折和门店满减
  1338. $wholeDiscountPrice = bcsub($modifyPrice, $runnerSendCost, 2);
  1339. $wholeDiscountPrice = bcsub(
  1340. $wholeDiscountPrice,
  1341. HdOrderClass::capSeckillExcludePrice($seckillGoodsPrice, $wholeDiscountPrice),
  1342. 2
  1343. );
  1344. $wholeDiscountNum = bcsub($unMeetBigNum, $seckillGoodsNum, 2);
  1345. if (bccomp($wholeDiscountNum, '0', 2) < 0) {
  1346. $wholeDiscountNum = 0;
  1347. }
  1348. $wholePick = WholeOrderDiscountClass::pick(
  1349. $wholeDiscountPrice,
  1350. $wholeDiscountNum,
  1351. $custom->discount ?? 1,
  1352. $shop
  1353. );
  1354. if ($wholePick['type'] === WholeOrderDiscountClass::TYPE_MEMBER) {
  1355. $post['skipShopMeetCut'] = 1;
  1356. } elseif ($wholePick['type'] === WholeOrderDiscountClass::TYPE_SHOP) {
  1357. $post['skipMemberDiscount'] = 1;
  1358. }
  1359. $return = \bizHd\order\services\OrderService::createHdOrder($post, $custom, $hasPay);
  1360. $orderSn = $return->orderSn ?? '';
  1361. if (!empty($orderSn) && (float)$unMeetSendCost > 0) {
  1362. $unMeetSendKey = 'hd_order_unmeet_send:' . $orderSn;
  1363. Yii::$app->redis->executeCommand('SETEX', [$unMeetSendKey, 864000, (string)$unMeetSendCost]);
  1364. }
  1365. if (!empty($hb)) {
  1366. $hb->status = 1;
  1367. $hb->orderId = $return->id;
  1368. $hb->save();
  1369. }
  1370. if ($return->sendType == 2) {
  1371. $ext = ShopExtClass::getByCondition(['shopId' => $return->shopId], true, null, 'id,shopId,thirdSend');
  1372. if (!empty($ext) && $ext->thirdSend == 1) {
  1373. util::fail('本店暂不能使用跑腿呢');
  1374. }
  1375. }
  1376. $transaction->commit();
  1377. $transactionFinished = true;
  1378. \bizHd\product\classes\ProductClass::clearLimitBuyRollbackSnapshot();
  1379. HomePageModuleClass::clearSeckillReservationSnapshot();
  1380. $orderSn = $return->orderSn ?? '';
  1381. // 优先 actPrice:门店满减落在 actPrice/orderPrice,避免仍按未减金额去支付
  1382. $orderPrice = $return->actPrice ?? ($return->orderPrice ?? 0);
  1383. $id = $return->id ?? 0;
  1384. $getPayType = dict::getDict('getPayType');
  1385. util::success([
  1386. 'orderSn' => $orderSn,
  1387. 'totalPrice' => $orderPrice,
  1388. 'couponId' => 0,
  1389. 'id' => $id,
  1390. 'getPayType' => $getPayType,
  1391. ]);
  1392. } catch (\Exception $e) {
  1393. $transaction->rollBack();
  1394. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  1395. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  1396. $transactionFinished = true;
  1397. Yii::error("合并下单失败:" . $e->getMessage());
  1398. util::fail('下单失败');
  1399. }
  1400. }
  1401. //下单要用到的相关信息 ssh 2019.12.6
  1402. public function actionOrderRelate()
  1403. {
  1404. $regionTree = RegionService::tree();
  1405. //门店名称
  1406. $shop = !empty($this->shop) ? $this->shop->attributes : [];
  1407. $sjName = $shop['merchantName'] ?? '';
  1408. $shopName = $shop['shopName'] ?? '';
  1409. $shop['showName'] = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  1410. $avatar = $shop['avatar'] ?? '';
  1411. $smallAvatar = imgUtil::groupImg($avatar) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
  1412. $shop['smallAvatar'] = $smallAvatar;
  1413. $freight = ['first' => 5, 'add' => 2];
  1414. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  1415. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  1416. util::success($out);
  1417. }
  1418. //余额支付 ssh 20250410
  1419. public function actionBalancePay()
  1420. {
  1421. $orderSn = Yii::$app->request->post('orderSn');
  1422. if (empty($orderSn)) {
  1423. util::fail('订单编号缺失');
  1424. }
  1425. //避免重复提交
  1426. util::checkRepeatCommit($orderSn, 5);
  1427. $connection = Yii::$app->db;
  1428. $transaction = $connection->beginTransaction();
  1429. try {
  1430. $fields = 'id,orderSn,shopId,sjId,mainId,customId,hdId,customName,shopAdminId,shopAdminName,status,payStatus,deadline,actPrice,realPrice,mainPay,cash,remainDebtPrice,onlinePay,fromType,sendType,showAddress,packingFee,sendCost,groupBuyId,thirdNo,hbId,hbAmount';
  1431. $order = OrderClass::getByCondition(['orderSn' => $orderSn], true, null, $fields);
  1432. if (empty($order)) {
  1433. util::fail('没有找到订单');
  1434. }
  1435. if ($order->shopId != $this->shopId) {
  1436. util::fail('不是你的订单');
  1437. }
  1438. //支付前验证订单有效性
  1439. OrderService::checkBeforePay($order);
  1440. $payWay = dict::getDict('payWay', 'balancePay');
  1441. \bizHd\order\classes\OrderClass::payAfter($order, $payWay);
  1442. $transaction->commit();
  1443. //解决重复通知,重要
  1444. $cacheKey = 'mall_order_balance_pay_' . $orderSn;
  1445. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1446. if (empty($has)) {
  1447. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 864000, 'has']);
  1448. //打印小票和语音播报
  1449. $fields = 'id,orderSn,shopId,mainId,customId,needPrint,payStatus,printNum,fromType,sendType,actPrice,addTime,sendNum,customName,shopAdminName,bookName,bookMobile,receiveUserName,receiveMobile,fullAddress,showAddress,reachDate,reachPeriod,anonymity,cardInfo,remark,goodsPrice,sendCost,serviceFee,labourCost,prePrice,orderPrice,discountAmount,realPrice,refundPrice,debt,remainDebtPrice,thirdSn,goodsNum';
  1450. $order = \bizHd\order\classes\OrderClass::getByCondition(['orderSn' => $orderSn], true, null, $fields);
  1451. if (!empty($order)) {
  1452. \bizHd\order\classes\OrderClass::onlinePrint($order);
  1453. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  1454. HdDeliveryOrderClass::payAfter($order);
  1455. $shopId = $order->shopId ?? 0;
  1456. $shop = ShopClass::getById($shopId, true);
  1457. if (in_array($order->fromType, [1, 3])) {
  1458. //您有新的收入提醒
  1459. WxMessageClass::gatheringIncomeInform($shop, $order);
  1460. }
  1461. if ($order->fromType == 2) {
  1462. //来自商城的新订单微信通知
  1463. WxMessageClass::hdNewOrderInform($shop, $order);
  1464. }
  1465. }
  1466. }
  1467. util::complete('支付成功');
  1468. } catch (\Exception $e) {
  1469. $transaction->rollBack();
  1470. Yii::error("支付原因:" . $e->getMessage());
  1471. util::fail('支付失败');
  1472. }
  1473. }
  1474. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  1475. public function actionWxPay()
  1476. {
  1477. ini_set('date.timezone', 'Asia/Shanghai');
  1478. $post = Yii::$app->request->post();
  1479. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1480. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1481. $order = OrderService::getByOrderSn($orderSn);
  1482. if (empty($order)) {
  1483. util::fail('订单号无效');
  1484. }
  1485. $orderId = $order['id'];
  1486. //验证优惠券是否还有效
  1487. if (!empty($couponId)) {
  1488. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  1489. }
  1490. //支付前验证订单有效性
  1491. OrderService::checkBeforePay($order);
  1492. $name = !empty($order['orderName']) ? $order['orderName'] : '购买花材';
  1493. $shop = $this->shop;
  1494. if (empty($shop)) {
  1495. util::fail('没有找到门店信息');
  1496. }
  1497. if (isset($shop->shopName) && !empty($shop->shopName)) {
  1498. $name .= '(' . $shop->shopName . ')';
  1499. }
  1500. $totalFee = $order['mainPay'];
  1501. $openId = '';
  1502. if (!empty($post['miniOpenId'])) {
  1503. $openId = $post['miniOpenId'];
  1504. //noticeUtil::push('散客买花时,通过前端获取了openId:' . $openId, '15280215347');
  1505. }
  1506. if (empty($openId)) {
  1507. if (isset($this->user['miniOpenId']) && !empty($this->user['miniOpenId'])) {
  1508. $openId = $this->user['miniOpenId'];
  1509. //noticeUtil::push('散客买花时,通过数据库获取了openId:' . $openId, '15280215347');
  1510. }
  1511. }
  1512. if (empty($openId)) {
  1513. util::fail('没有找到openId');
  1514. }
  1515. $now = time();
  1516. $expireTime = $now + 1800;
  1517. $updateData = [];
  1518. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1519. $oldOrderSn = $orderSn;
  1520. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1521. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1522. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1523. $params = [
  1524. 'appid' => 'OP00002119',
  1525. 'serial_no' => '018b08cfddbd',
  1526. 'merchant_no' => $shop->lklSjNo,
  1527. 'term_no' => $shop->lklScanTermNo,
  1528. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1529. 'lklCertificatePath' => $lklCertificatePath,
  1530. ];
  1531. $laResource = new Lakala($params);
  1532. $closeParams = [
  1533. 'orderSn' => $oldOrderSn,
  1534. ];
  1535. $response = $laResource->close($closeParams);
  1536. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1537. $msg = $response['msg'] ?? '';
  1538. $lklSjNo = $shop->lklSjNo ?? '';
  1539. noticeUtil::push('重点注意,散客买花更换单号没有成功,单号:' . $oldOrderSn . ',关单没有成功,' . $msg . '。商户号:' . $lklSjNo, '15280215347');
  1540. util::fail('出错了哦,请重新下一单');
  1541. }
  1542. $orderSn = orderSn::getOrderSn();
  1543. $updateData['orderSn'] = $orderSn;
  1544. OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
  1545. // 附加运费缓存挂在下单号上,换号后需迁移,否则支付成功无法写入附加费冷却锁
  1546. \bizHd\order\classes\PsMethodClass::migrateUnMeetSendCostCache($oldOrderSn, $orderSn);
  1547. } else {
  1548. //已请求的不能再修改价格
  1549. $updateData['modPrice'] = 0;
  1550. }
  1551. if (empty($order['deadline'])) {
  1552. $updateData['deadline'] = $expireTime;
  1553. }
  1554. if (!empty($updateData)) {
  1555. OrderService::updateById($orderId, $updateData);
  1556. }
  1557. if (bccomp((string)$totalFee, '0', 2) == 1) {
  1558. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1559. $sjExtend = WxOpenClass::getMallWxInfo();
  1560. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1561. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1562. $params = [
  1563. 'appid' => 'OP00002119',
  1564. 'serial_no' => '018b08cfddbd',
  1565. 'merchant_no' => $shop->lklSjNo,
  1566. 'term_no' => $shop->lklScanTermNo,
  1567. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1568. 'lklCertificatePath' => $lklCertificatePath,
  1569. ];
  1570. $laResource = new Lakala($params);
  1571. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  1572. $wxParams = [
  1573. 'orderSn' => $orderSn,
  1574. 'amount' => $totalFee,
  1575. 'capitalType' => $capitalType,
  1576. 'notifyUrl' => $notifyUrl,
  1577. 'wxAppId' => $sjExtend['miniAppId'],
  1578. 'openId' => $openId,
  1579. 'subject' => $name,
  1580. 'couponId' => $couponId,
  1581. ];
  1582. $response = $laResource->driveWxPay($wxParams);
  1583. if(!isset($response['code']) || $response['code'] != 'BBS00000') {
  1584. $errMsg = $response['msg'] ?? '';
  1585. noticeUtil::push($errMsg, '15280215347');
  1586. util::fail('支付失败');
  1587. }
  1588. } else if (bccomp((string)$totalFee, '0.00', 2) == 0){
  1589. Yii::info('付款金额为0');
  1590. $connection = Yii::$app->db;
  1591. $transaction = $connection->beginTransaction();
  1592. try {
  1593. OrderClass::completeZeroAmountPay($orderId);
  1594. $transaction->commit();
  1595. } catch (\Exception $e) {
  1596. $transaction->rollBack();
  1597. Yii::error('零元订单支付后续失败:' . $e->getMessage());
  1598. util::fail('支付失败');
  1599. }
  1600. $cacheKey = 'mall_order_zero_pay_' . $orderSn;
  1601. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1602. if (empty($has)) {
  1603. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 864000, 'has']);
  1604. $paidOrder = HdOrderClass::getByCondition(['orderSn' => $orderSn], true);
  1605. if (!empty($paidOrder)) {
  1606. HdOrderClass::onlinePrint($paidOrder);
  1607. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  1608. HdDeliveryOrderClass::payAfter($paidOrder);
  1609. $shopId = $paidOrder->shopId ?? 0;
  1610. $shop = ShopClass::getById($shopId, true);
  1611. $shopExt = \biz\shop\classes\ShopExtClass::getByCondition(['shopId' => $shopId], true);
  1612. if (!empty($shopExt) && $shopExt->needWork == 1 && $paidOrder->hasWork != 1 && !empty($shop)) {
  1613. $mainId = $shop->mainId ?? 0;
  1614. $main = \bizHd\shop\classes\MainClass::getById($mainId, true);
  1615. \bizHd\work\classes\WorkClass::needWork($paidOrder, $main);
  1616. $hasWork = \bizHd\work\classes\WorkClass::getByCondition(['orderId' => $orderId], true);
  1617. if (!empty($hasWork)) {
  1618. $paidOrder->hasWork = 1;
  1619. $paidOrder->save();
  1620. }
  1621. \biz\shop\classes\ShopExtClass::newWorkRemind($shopExt, $paidOrder);
  1622. }
  1623. if (!empty($shop)) {
  1624. WxMessageClass::hdNewOrderInform($shop, $paidOrder);
  1625. }
  1626. }
  1627. }
  1628. $new = [
  1629. 'id' => $orderId,
  1630. 'orderSn' => $orderSn,
  1631. ];
  1632. util::error(errCode::ORDER_PAY_AMOUNT_ZERO, '付款金额为0', $new);
  1633. } else {
  1634. util::fail('付款金额不能为负数');
  1635. }
  1636. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  1637. $appId = $newParams['app_id'] ?? '';
  1638. $nonceStr = $newParams['nonce_str'] ?? '';
  1639. $paySign = $newParams['pay_sign'] ?? '';
  1640. $package = $newParams['package'] ?? '';
  1641. $signType = $newParams['sign_type'] ?? '';
  1642. $timeStamp = $newParams['time_stamp'] ?? '';
  1643. $new = [
  1644. 'id' => $orderId,
  1645. 'appId' => $appId,
  1646. 'nonceStr' => $nonceStr,
  1647. 'paySign' => $paySign,
  1648. 'package' => $package,
  1649. 'signType' => $signType,
  1650. 'timeStamp' => $timeStamp,
  1651. 'orderSn' => $orderSn,
  1652. ];
  1653. util::success($new);
  1654. }
  1655. //快捷付款订单
  1656. public function actionFastPay()
  1657. {
  1658. ini_set('date.timezone', 'Asia/Shanghai');
  1659. $post = Yii::$app->request->post();
  1660. $payWay = $post['payWay'] ?? 0;
  1661. $shopId = $this->shopId;
  1662. $shop = $this->shop;
  1663. if (empty($shop)) {
  1664. util::fail('没有门店信息');
  1665. }
  1666. $customId = $this->customId;
  1667. $custom = $this->custom;
  1668. $hdId = $this->hdId;
  1669. $hd = $this->hd;
  1670. if (empty($customId) || empty($hdId)) {
  1671. //考虑没有登录时的付款
  1672. $defaultCustomId = $shop->defaultCustomId ?? 0;
  1673. if (empty($defaultCustomId)) {
  1674. util::fail('请设置快捷开单的客户');
  1675. }
  1676. $customId = $defaultCustomId;
  1677. $custom = CustomClass::getById($defaultCustomId, true);
  1678. if (empty($custom)) {
  1679. util::fail('无效的快捷客户');
  1680. }
  1681. $hdId = $custom->hdId;
  1682. $hd = \bizMall\hd\classes\HdClass::getById($hdId, true);
  1683. if (empty($hd)) {
  1684. util::fail('没有花店信息呢!');
  1685. }
  1686. }
  1687. $post['hdId'] = $hdId;
  1688. $post['hdName'] = $hd->name ?? '';
  1689. $customName = $custom->name ?? '';
  1690. $customPy = $custom->py ?? '';
  1691. $post['customName'] = $customName;
  1692. $post['customNamePy'] = $customPy;
  1693. $post['shopId'] = $shopId;
  1694. $post['mainId'] = $this->mainId;
  1695. $post['customId'] = $customId;
  1696. $prePrice = round($post['prePrice'], 2);
  1697. $actPrice = $prePrice;
  1698. if ($actPrice <= 0) {
  1699. util::fail('请填写付款金额');
  1700. }
  1701. $post['actPrice'] = $actPrice;
  1702. $post['userId'] = $this->userId;
  1703. $now = time();
  1704. $expireTime = $now + 300;//订单5分钟后过期
  1705. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1706. $post['deadline'] = date("Y-m-d H:i:s", $expireTime);
  1707. $order = ScanPayClass::addOrder($post);
  1708. $orderId = $order->id ?? 0;
  1709. $orderSn = $order->orderSn ?? '';
  1710. $capitalType = dict::getDict('capitalType', 'scanPay', 'id');
  1711. if ($payWay == 0) {
  1712. //微信
  1713. $name = '购买鲜花,扫码付款';
  1714. $totalFee = $actPrice;
  1715. $user = UserService::getById($this->userId);
  1716. //小程序使用miniOpenId
  1717. $openId = $user['miniOpenId'];
  1718. if (empty($openId)) {
  1719. $openId = !empty($post['miniOpenId']) ? $post['miniOpenId'] : '';
  1720. }
  1721. if (empty($openId)) {
  1722. util::fail('没有微信信息');
  1723. }
  1724. $sjExtend = WxOpenClass::getMallWxInfo();
  1725. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1726. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1727. $params = [
  1728. 'appid' => 'OP00002119',
  1729. 'serial_no' => '018b08cfddbd',
  1730. 'merchant_no' => $shop->lklSjNo,
  1731. 'term_no' => $shop->lklScanTermNo,
  1732. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1733. 'lklCertificatePath' => $lklCertificatePath,
  1734. ];
  1735. $laResource = new Lakala($params);
  1736. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  1737. $wxParams = [
  1738. 'orderSn' => $orderSn,
  1739. 'amount' => $totalFee,
  1740. 'capitalType' => $capitalType,
  1741. 'notifyUrl' => $notifyUrl,
  1742. 'wxAppId' => $sjExtend['miniAppId'],
  1743. 'openId' => $openId,
  1744. 'subject' => $name,
  1745. 'couponId' => 0,
  1746. ];
  1747. $response = $laResource->driveWxPay($wxParams);
  1748. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1749. $errMsg = $response['msg'] ?? '';
  1750. noticeUtil::push($errMsg, '15280215347');
  1751. util::fail('支付失败');
  1752. }
  1753. $newParams = $response['resp_data']['acc_resp_fields'] ?? [];
  1754. $appId = $newParams['app_id'] ?? '';
  1755. $nonceStr = $newParams['nonce_str'] ?? '';
  1756. $paySign = $newParams['pay_sign'] ?? '';
  1757. $package = $newParams['package'] ?? '';
  1758. $signType = $newParams['sign_type'] ?? '';
  1759. $timeStamp = $newParams['time_stamp'] ?? '';
  1760. $new = [
  1761. 'id' => $orderId,
  1762. 'appId' => $appId,
  1763. 'nonceStr' => $nonceStr,
  1764. 'paySign' => $paySign,
  1765. 'package' => $package,
  1766. 'signType' => $signType,
  1767. 'timeStamp' => $timeStamp,
  1768. 'orderSn' => $orderSn,
  1769. ];
  1770. util::success($new);
  1771. } elseif ($payWay == 1) {
  1772. //支付宝
  1773. $totalFee = $actPrice;
  1774. $subject = '购买鲜花,扫码付款';
  1775. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1776. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1777. $params = [
  1778. 'appid' => 'OP00002119',
  1779. 'serial_no' => '018b08cfddbd',
  1780. 'merchant_no' => $shop->lklSjNo,
  1781. 'term_no' => $shop->lklB2BTermNo,
  1782. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1783. 'lklCertificatePath' => $lklCertificatePath,
  1784. ];
  1785. $laResource = new Lakala($params);
  1786. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/cash-pay-callback";
  1787. $cashParams = [
  1788. 'orderSn' => $orderSn,
  1789. 'amount' => $totalFee,
  1790. 'capitalType' => $capitalType,
  1791. 'notifyUrl' => $notifyUrl,
  1792. 'subject' => $subject,
  1793. ];
  1794. $response = $laResource->cashierPay($cashParams);
  1795. if (!isset($response['code']) || $response['code'] != '000000') {
  1796. util::fail('支付失败了');
  1797. }
  1798. $url = $response['resp_data']['counter_url'] ?? '';
  1799. if (empty($url)) {
  1800. util::fail('支付失败');
  1801. }
  1802. util::success(['url' => $url]);
  1803. } elseif ($payWay == 2) {
  1804. //余额支付
  1805. util::fail('暂不支持');
  1806. } else {
  1807. util::fail('无效的支付方式');
  1808. }
  1809. }
  1810. /**
  1811. * 订单列表
  1812. * 拼团单含 groupBuyStatus,供 mallApp 订单 Tab / 店铺订单控制履约按钮与状态文案
  1813. */
  1814. public function actionList()
  1815. {
  1816. $get = Yii::$app->request->get();
  1817. $status = $get['status'] ?? 0;
  1818. $hdId = $get['hdId'] ?? 0;
  1819. $userId = $this->userId;
  1820. $where = ['userId' => $userId];
  1821. if (!empty($status)) {
  1822. $where['status'] = $status;
  1823. }
  1824. if (!empty($hdId)) {
  1825. $hd = \bizMall\hd\classes\HdClass::getById($hdId, true);
  1826. if (empty($hd)) {
  1827. util::fail('无效的花店');
  1828. }
  1829. if ($hd['userId'] != $userId) {
  1830. util::fail('不是你的花店');
  1831. }
  1832. $where['hdId'] = $hdId;
  1833. }
  1834. $list = OrderService::getOrderList($where);
  1835. util::success($list);
  1836. }
  1837. //订单评价
  1838. public function actionComment()
  1839. {
  1840. $post = Yii::$app->request->post();
  1841. $id = $post['id'];
  1842. $order = OrderClass::getById($id);
  1843. if ($order['grade'] > 0) {
  1844. util::fail('您已经评过了');
  1845. }
  1846. OrderService::comment($post);
  1847. util::complete('提交成功');
  1848. }
  1849. /**
  1850. * 订单详情:含 canApplyRefund / refundApplyId / groupBuyStatus
  1851. * 拼团单不能只看 status、payStatus,前端须结合 groupBuyStatus(1拼团中 2成功 3失败 4已取消)
  1852. */
  1853. public function actionDetail()
  1854. {
  1855. $id = Yii::$app->request->get('id', 0);
  1856. $detail = OrderClass::getOrderById($id);
  1857. $userId = $this->userId;
  1858. if ($detail['userId'] != $userId) {
  1859. util::fail('不是你的单,不能查看');
  1860. }
  1861. $shOrderMap = [];
  1862. if ($detail['hasForward'] == 1) {
  1863. $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
  1864. }
  1865. $detail['shOrderMap'] = $shOrderMap;
  1866. //是否显示余额支付按钮 ssh 20260120
  1867. $hd = $this->hd;
  1868. $balance = $hd->balance ?? 0;
  1869. $showYePay = $balance > 0 ? 1 : 0;
  1870. $detail['showYePay'] = $showYePay;
  1871. $detail['balance'] = $balance;
  1872. $detail['rechargeWeal'] = $this->shop->rechargeWeal; //是否开启余额支付
  1873. // 与 RefundController::canApplyRefund 对齐;最新申请供详情页「查看申请」入口
  1874. $detail['distOrderSettled'] = DistributionOrderClass::isDistOrderSettled((int)$id) ? 1 : 0;
  1875. $apply = HdRefundClass::getLatestByOrderId((int)$id);
  1876. $detail['canApplyRefund'] = $this->canApplyRefundForDetail($detail, $apply) ? 1 : 0;
  1877. $detail['refundApplyId'] = 0;
  1878. $detail['refundApplyStatus'] = '';
  1879. $detail['refundApplyStatusText'] = '';
  1880. // 有顾客申请才给入口;商家即时售后 userId=0 不展示「查看申请」
  1881. if (!empty($apply) && !empty($apply['id'])) {
  1882. $detail['refundApplyId'] = (int)$apply['id'];
  1883. $detail['refundApplyStatus'] = (int)($apply['status'] ?? 0);
  1884. $detail['refundApplyStatusText'] = HdRefundMallClass::statusText($apply['status'] ?? 0);
  1885. }
  1886. // 配送方式名称:xhPsMethod.name(style = 订单 sendType)
  1887. $detail['psMethodName'] = $this->resolvePsMethodName($detail);
  1888. util::success($detail);
  1889. }
  1890. /**
  1891. * 解析订单配送方式名称(xhPsMethod.name,无记录时回退字典默认名)
  1892. * @param array $order 订单详情
  1893. * @return string
  1894. */
  1895. protected function resolvePsMethodName($order)
  1896. {
  1897. $mainId = (int)($order['mainId'] ?? 0);
  1898. $style = (int)($order['sendType'] ?? 0);
  1899. if ($mainId > 0) {
  1900. $psMethod = PsMethodClass::getByCondition([
  1901. 'mainId' => $mainId,
  1902. 'style' => $style,
  1903. ]);
  1904. if (!empty($psMethod['name'])) {
  1905. return (string)$psMethod['name'];
  1906. }
  1907. }
  1908. $default = dict::getDict('shMethod', $style);
  1909. return (string)($default['name'] ?? '');
  1910. }
  1911. /**
  1912. * 订单详情是否可申请售后(与 mall RefundController::canApplyRefund 规则一致)
  1913. * 现金为 0 时:红包仍挂单(hbId>0)且红包金额大于订单实付(hbAmount>mainPay)才允许申请
  1914. * @param array $order 订单详情
  1915. * @param array|null $apply 最新顾客申请,避免详情里重复查
  1916. * @return bool
  1917. */
  1918. protected function canApplyRefundForDetail($order, $apply = null)
  1919. {
  1920. if ((int)($order['payStatus'] ?? 0) !== 1) {
  1921. return false;
  1922. }
  1923. $status = (int)($order['status'] ?? 0);
  1924. if (in_array($status, [HdOrderClass::ORDER_STATUS_UN_PAY, HdOrderClass::ORDER_STATUS_CANCEL, 6], true)) {
  1925. return false;
  1926. }
  1927. // 拼团单须成团成功才开放售后;拼团中/失败/已取消走自动退款或不可履约
  1928. if ((int)($order['groupBuyId'] ?? 0) > 0
  1929. && (int)($order['groupBuyStatus'] ?? 0) !== GroupBuyClass::STATUS_SUCCESS) {
  1930. return false;
  1931. }
  1932. if ((int)($order['forward'] ?? 0) === 1) {
  1933. return false;
  1934. }
  1935. if ($apply === null) {
  1936. $apply = HdRefundClass::getLatestByOrderId((int)($order['id'] ?? 0));
  1937. }
  1938. if (!empty($apply) && (int)($apply['status'] ?? -1) === HdRefundClass::STATUS_PENDING) {
  1939. return false;
  1940. }
  1941. if (DistributionOrderClass::isDistOrderSettled((int)($order['id'] ?? 0))) {
  1942. return false;
  1943. }
  1944. // 可退现金>0 可申请;现金为 0 时需红包未退回且红包金额大于实付
  1945. if (!HdRefundMallClass::hasRefundableAmount($order)) {
  1946. return false;
  1947. }
  1948. return true;
  1949. }
  1950. /**
  1951. * 库存不足:以 code=-1 返回商品标识、剩余库存与超出数量。
  1952. * 与限购超限同形态,供混合结算页/购物车红框高亮对应商品并提示超出多少。
  1953. *
  1954. * @param array $opts productId/goodsId/specGoodsId/property/activityType/stock/num
  1955. */
  1956. protected function failStockExceed($opts)
  1957. {
  1958. $productId = intval($opts['productId'] ?? 0);
  1959. $goodsId = intval($opts['goodsId'] ?? 0);
  1960. $specGoodsId = intval($opts['specGoodsId'] ?? 0);
  1961. $property = intval($opts['property'] ?? 0);
  1962. $activityType = strval($opts['activityType'] ?? '');
  1963. $stock = floatval($opts['stock'] ?? 0);
  1964. $num = floatval($opts['num'] ?? 0);
  1965. if (bccomp($stock, '0', 2) < 0) {
  1966. $stock = 0;
  1967. }
  1968. $exceed = bcsub($num, $stock, 2);
  1969. if (bccomp($exceed, '0', 2) < 0) {
  1970. $exceed = '0';
  1971. }
  1972. $stockShow = rtrim(rtrim(sprintf('%.2f', $stock), '0'), '.');
  1973. if ($stockShow === '') {
  1974. $stockShow = '0';
  1975. }
  1976. $msg = $activityType === 'seckill'
  1977. ? "秒杀商品库存不足,剩余{$stockShow}"
  1978. : "商品库存不足,剩余{$stockShow}";
  1979. util::error(-1, $msg, [
  1980. 'productId' => $productId,
  1981. 'goodsId' => $goodsId,
  1982. 'specGoodsId' => $specGoodsId,
  1983. 'property' => $property,
  1984. 'activityType' => $activityType,
  1985. 'reason' => 'stock',
  1986. 'stock' => floatval($stock),
  1987. 'num' => $num,
  1988. 'exceed' => floatval($exceed),
  1989. ]);
  1990. }
  1991. //获取详情 ssh 20220512
  1992. public function actionInfo()
  1993. {
  1994. $sn = Yii::$app->request->get('orderSn', '');
  1995. $detail = OrderClass::getOrderBySn($sn);
  1996. util::success($detail);
  1997. }
  1998. }