OrderController.php 93 KB

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