OrderController.php 92 KB

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