OrderController.php 94 KB

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