OrderController.php 92 KB

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