OrderController.php 86 KB

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