OrderController.php 94 KB

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