OrderController.php 95 KB

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