OrderController.php 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095
  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. */
  830. public function actionCreateMixOrder()
  831. {
  832. $post = Yii::$app->request->post();
  833. $post['sjId'] = $this->sjId;
  834. $post['shopId'] = $this->shopId;
  835. $post['payWay'] = 0;
  836. $post['mainId'] = $this->mainId ?? 0;
  837. $post['userId'] = $this->userId ?? 0;
  838. $userId = $this->userId;
  839. util::checkRepeatCommit($userId, 3);
  840. $mainId = $this->mainId;
  841. $shop = $this->shop;
  842. $openShop = \bizHd\shop\classes\ShopClass::getOpenShop($shop);
  843. if ($openShop == 0) {
  844. util::fail('已休店');
  845. }
  846. $hdId = $post['hdId'] ?? 0;
  847. $hd = HdClass::getById($hdId, true);
  848. if (empty($hd)) {
  849. util::fail('没有找到花店');
  850. }
  851. if ($hd->shopId != $this->shopId) {
  852. util::fail('不是你的花店');
  853. }
  854. $post['hdName'] = $hd->name ?? '';
  855. // 合并结算沿用花材购物车的客户身份(花店客户)
  856. $hdCustomId = $hd->customId ?? 0;
  857. $custom = CustomClass::getById($hdCustomId, true);
  858. if (empty($custom)) {
  859. util::fail('没有找到客户');
  860. }
  861. $customName = $custom->name;
  862. $post['customId'] = $hdCustomId;
  863. $post['customName'] = $customName;
  864. $post['customNamePy'] = stringUtil::py($customName);
  865. $productJson = $post['product'];
  866. if (empty($productJson)) {
  867. util::fail('请选择商品');
  868. }
  869. $productList = json_decode($productJson, true);
  870. if (empty($productList) || !is_array($productList)) {
  871. util::fail('请选择商品');
  872. }
  873. $itemRows = []; // 所有花材
  874. $goodsRows = []; // 所有花束
  875. foreach ($productList as $idx => $row) {
  876. $property = intval($row['property'] ?? -1);
  877. if ($property === 1) {
  878. $itemRows[$idx] = $row;
  879. } elseif ($property === 0) {
  880. $goodsRows[$idx] = $row;
  881. } else {
  882. util::fail('商品类型错误');
  883. }
  884. }
  885. if (empty($itemRows) && empty($goodsRows)) {
  886. util::fail('请选择商品');
  887. }
  888. // ---- 花材校验与定价 ----
  889. $productInfoList = [];
  890. if (!empty($itemRows)) {
  891. $ids = array_unique(array_filter(array_map(function ($r) {
  892. return intval($r['productId'] ?? 0);
  893. }, $itemRows)));
  894. $productInfoList = ProductClass::getByIds($ids, null, 'id');
  895. if (empty($productInfoList)) {
  896. util::fail('花材不存在');
  897. }
  898. $presellData = [];
  899. $nowTime = strtotime(date("Y-m-d"));
  900. foreach ($productInfoList as $currentInfo) {
  901. if (!isset($currentInfo['mainId']) || $currentInfo['mainId'] != $this->mainId) {
  902. util::fail('只能选一家的商品,请清空重新选呢');
  903. }
  904. $presell = $currentInfo['presell'] ?? 0;
  905. $presellData[] = $presell;
  906. if ($presell == 1) {
  907. if (empty($post['reachDate'])) {
  908. util::fail('请选择配送或取货日期');
  909. }
  910. $sendTimeWant = $post['reachDate'];
  911. if (strtotime($sendTimeWant) < $nowTime) {
  912. util::fail('不能选择过去时间');
  913. }
  914. $hasDateStr = $currentInfo['presellDate'] ?? [];
  915. $hasDate = explode(',', trim($hasDateStr));
  916. if (empty($hasDate)) {
  917. util::fail('预售日期有问题,请提醒门店');
  918. }
  919. if (!in_array(strtotime($sendTimeWant), $hasDate)) {
  920. util::fail("有预售花材在{$sendTimeWant}没到货");
  921. }
  922. $post['presell'] = 1;
  923. }
  924. }
  925. if (count($productInfoList) != count($ids)) {
  926. util::fail('存在无效花材');
  927. }
  928. $presellData = array_unique($presellData);
  929. if (count($presellData) > 1) {
  930. util::fail('预售和非预售花材不能一起下单');
  931. }
  932. }
  933. $connection = Yii::$app->db;
  934. $transaction = $connection->beginTransaction();
  935. $transactionFinished = false;
  936. register_shutdown_function(function () use (&$transactionFinished, $transaction) {
  937. if ($transactionFinished) {
  938. return;
  939. }
  940. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  941. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  942. if ($transaction->isActive) {
  943. $transaction->rollBack();
  944. }
  945. });
  946. try {
  947. $orderValidTime = !getenv('ORDER_VALID_TIME') ? 600 : getenv('ORDER_VALID_TIME'); // TODO 找少华确认 -- 测试环境是 600
  948. $post['deadline'] = time() + $orderValidTime;
  949. $post['reachDate'] = !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  950. $post['needPrint'] = dict::getDict('needPrint', 'need');
  951. $post['fromType'] = dict::getDict('fromType', 'mall');
  952. $post['store'] = 0;
  953. $user = $this->user;
  954. $post['bookMobile'] = $user->mobile ?? '';
  955. $post['bookName'] = $user->name ?? '';
  956. $hasPay = 0;
  957. $modifyPrice = 0;
  958. $totalWeight = 0;
  959. $totalNum = 0;
  960. $itemBigNum = 0;
  961. $totalReachDiscount = 0;
  962. $resolvedProduct = [];
  963. $hasSeckillGoods = false;
  964. // 秒杀商品行合计:供会员折/门店满减剔除,避免活动价再叠整单优惠
  965. $seckillGoodsPrice = 0;
  966. // 秒杀花束份数:不计入门店满减件数门槛,最低消费数量仍按整单份数
  967. $seckillGoodsNum = 0;
  968. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  969. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  970. $post['orderType'] = 0;
  971. foreach ($productList as $eleKey => $element) {
  972. $property = $element['property']; // 1: 花材, 0: 花束
  973. if ($property === 1) { // 花材
  974. $level = 0;
  975. $productId = $element['productId'];
  976. $product = $productInfoList[$productId] ?? null;
  977. if (empty($product)) {
  978. util::fail('有花材信息没有找到');
  979. }
  980. $num = $element['num'] ?? 0;
  981. $limitKey = \bizHd\product\classes\ProductClass::LIMIT_BUY_KEY . $productId;
  982. $hasBuyNum = Yii::$app->redis->executeCommand('HGET', [$limitKey, $hdCustomId]);
  983. $hasBuyNum = $num + ($hasBuyNum == null ? 0 : $hasBuyNum);
  984. $price = \bizGhs\product\classes\ProductClass::getFinalPrice($product, $level, $priceMap, $addPriceMap, 0, $num, $hasBuyNum);
  985. $reachNum = $product['reachNum'] ?? 0;
  986. $reachNumDiscount = $product['reachNumDiscount'] ?? 0;
  987. if ($reachNum > 0 && $num >= $reachNum && $reachNumDiscount > 0) {
  988. $currentReachDiscount = bcmul($reachNumDiscount, $num, 2);
  989. $totalReachDiscount = bcadd($totalReachDiscount, $currentReachDiscount, 2);
  990. }
  991. $currentTotal = bcmul($price, $num, 2);
  992. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  993. $weight = $product['weight'] ?? 0;
  994. $currentWeight = bcmul($num, $weight, 2);
  995. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  996. $totalNum = bcadd($totalNum, $num);
  997. $itemBigNum = bcadd($itemBigNum, $num);
  998. if (($product['limitBuy'] ?? 0) > 0) {
  999. $product['productId'] = $productId;
  1000. \bizHd\product\classes\ProductClass::handleLimitBuy($product, $hdCustomId, floatval($num));
  1001. }
  1002. $resolvedProduct[] = [
  1003. 'productId' => $productId,
  1004. 'num' => $num,
  1005. 'itemId' => $element['itemId'] ?? 0,
  1006. 'unitType' => $element['unitType'] ?? 0,
  1007. 'property' => 1,
  1008. 'unitPrice' => $price,
  1009. ];
  1010. } else if ($property === 0) { // 花束
  1011. $goodsId = $element['goodsId']; // 主商品ID
  1012. $specGoodsId = $element['specGoodsId']; // 规格ID
  1013. $saleGoodsId = $element['productId']; // 记录用于销售的商品ID,通常为具体的规格或产品ID
  1014. $goodsNum = isset($element['num']) && $element['num'] > 0 ? $element['num'] : 1;
  1015. if ($goodsId <= 0 && $saleGoodsId > 0) {
  1016. $probe = GoodsClass::getById($saleGoodsId, true);
  1017. if (!empty($probe)) {
  1018. $masterId = intval($probe->masterId);
  1019. if ($masterId > 0) {
  1020. $goodsId = $masterId;
  1021. $specGoodsId = $saleGoodsId;
  1022. } else {
  1023. $goodsId = $saleGoodsId;
  1024. }
  1025. }
  1026. }
  1027. if ($goodsId <= 0) {
  1028. util::fail('请选择花束商品');
  1029. }
  1030. $goodsInfo = GoodsClass::getById($goodsId, true);
  1031. if (empty($goodsInfo)) {
  1032. util::fail('没有找到花束商品');
  1033. }
  1034. if ($goodsInfo->mainId != $mainId) {
  1035. util::fail('不是你的商品');
  1036. }
  1037. if ($specGoodsId > 0) {
  1038. // 首规格落在主记录:specGoodsId 可以等于主商品 id,直接用主记录行售卖
  1039. if ($specGoodsId != $goodsId) {
  1040. $specGoods = GoodsClass::getById($specGoodsId, true);
  1041. if (empty($specGoods) || $specGoods->mainId != $mainId || $specGoods->masterId != $goodsId || $specGoods->delStatus != 0 || $specGoods->status != 1) {
  1042. util::fail('规格不可用');
  1043. }
  1044. $goodsInfo = $specGoods;
  1045. $saleGoodsId = $specGoodsId;
  1046. } else {
  1047. $saleGoodsId = $goodsId;
  1048. }
  1049. } else {
  1050. if ((int)($goodsInfo->masterId ?? 0) === 0 && (int)($goodsInfo->goodsStyle ?? 0) === 1) {
  1051. util::fail('请选择规格');
  1052. }
  1053. $saleGoodsId = $goodsId;
  1054. }
  1055. $stock = $goodsInfo->stock;
  1056. $stockSet = $goodsInfo->stockSet;
  1057. if ($stockSet == 1 && $stock <= 0) {
  1058. util::fail('花束库存不足');
  1059. }
  1060. // 秒杀商品:不信任前端传的价格,独立回查秒杀配置核实活动状态/库存/限购后再核价
  1061. $seckillRow = null;
  1062. $seckillActivityGoodsId = 0;
  1063. if (strval($element['activityType'] ?? '') === 'seckill') {
  1064. $seckillRow = HomePageModuleClass::getSeckillActiveRow($mainId, intval($this->shopId), $saleGoodsId);
  1065. if (empty($seckillRow)) {
  1066. util::fail('秒杀活动已结束或商品已下架,请重新选择');
  1067. }
  1068. $seckillActivityGoodsId = intval($seckillRow['id'] ?? ($seckillRow['activityGoodsId'] ?? 0));
  1069. if ($seckillActivityGoodsId <= 0) {
  1070. util::fail('秒杀商品版本无效,请重新选择');
  1071. }
  1072. $seckillStock = floatval($seckillRow['stock']);
  1073. $soldCount = HomePageModuleClass::getSeckillSoldCount($mainId, $seckillActivityGoodsId);
  1074. if (bcadd($soldCount, $goodsNum, 2) > $seckillStock) {
  1075. util::fail('秒杀库存不足,请重新选择');
  1076. }
  1077. $seckillLimit = floatval($seckillRow['limit'] ?? 0);
  1078. if ($seckillLimit > 0) {
  1079. $boughtCount = HomePageModuleClass::getSeckillCustomBoughtCount($mainId, $seckillActivityGoodsId, $hdCustomId); // TODO 同一个商品,如果缓存没有合理清除,就会一直限购
  1080. if (bcadd($boughtCount, $goodsNum, 2) > $seckillLimit) {
  1081. util::fail("秒杀商品每人限购{$seckillLimit}件,已超出可购买数量");
  1082. }
  1083. }
  1084. }
  1085. $goodsData = $goodsInfo->attributes;
  1086. if ($seckillRow) {
  1087. $unitPrice = floatval($seckillRow['price'] ?? 0);
  1088. if ($unitPrice <= 0) {
  1089. util::fail('秒杀价格异常,不能下单');
  1090. }
  1091. } else {
  1092. $ret = \bizHd\goods\classes\GoodsClass::getFinalPrice($goodsData, $shop, $custom, []);
  1093. $priceType = $ret['priceType'] ?? 0;
  1094. if ($priceType == 0) {
  1095. util::fail('花束没有价格,不能下单');
  1096. }
  1097. $unitPrice = $ret['price'] ?? 0;
  1098. if ($unitPrice <= 0) {
  1099. util::fail('花束没有价格,不能下单');
  1100. }
  1101. }
  1102. if ($seckillRow) {
  1103. // 通过校验后立即预占名额,失败/异常时随事务一起回滚(见 register_shutdown_function)
  1104. HomePageModuleClass::reserveSeckillPurchase($mainId, $seckillActivityGoodsId, $hdCustomId, $goodsNum);
  1105. $hasSeckillGoods = true;
  1106. }
  1107. $currentTotal = bcmul($unitPrice, $goodsNum, 2);
  1108. $modifyPrice = bcadd($modifyPrice, $currentTotal, 2);
  1109. if ($seckillRow) {
  1110. $seckillGoodsPrice = bcadd($seckillGoodsPrice, $currentTotal, 2);
  1111. $seckillGoodsNum = bcadd($seckillGoodsNum, $goodsNum, 2);
  1112. }
  1113. $weight = $goodsInfo->weight ?? 0;
  1114. if ($weight > 5) {
  1115. $weight = 5;
  1116. }
  1117. $currentWeight = bcmul($weight, $goodsNum, 2);
  1118. $totalWeight = bcadd($totalWeight, $currentWeight, 2);
  1119. $totalNum = bcadd($totalNum, $goodsNum);
  1120. $resolvedProduct[] = [
  1121. 'productId' => $saleGoodsId,
  1122. 'unitType' => 0,
  1123. 'property' => 0,
  1124. // 花束是否包运费:供跑腿运费分支判断(1=包运费)
  1125. 'freightType' => (int)($goodsInfo->freightType ?? 0),
  1126. 'unitPrice' => $unitPrice,
  1127. 'num' => $goodsNum,
  1128. 'seckillGoodsId' => $seckillActivityGoodsId,
  1129. ];
  1130. } else {
  1131. util::fail('商品类型错误');
  1132. }
  1133. }
  1134. // 根据 $resolvedProduct 设置订单类型:1纯花束 2纯花材 3混合
  1135. $properties = array_unique(array_column($resolvedProduct, 'property'));
  1136. if (count($properties) === 1) {
  1137. $post['orderType'] = intval($properties[0]) === 0 ? 1 : 2;
  1138. } elseif (count($properties) > 1) {
  1139. $post['orderType'] = 3;
  1140. }
  1141. $post['product'] = $resolvedProduct;
  1142. $post['reachDiscountPrice'] = $totalReachDiscount;
  1143. $goodsOnlyPrice = $modifyPrice;
  1144. unset($post['sendCost'], $post['packCost'], $post['packingFee'], $post['unMeetSendCost']);
  1145. $sendType = intval($post['sendType'] ?? 0);
  1146. $customInfo = \bizHd\order\classes\PsMethodClass::buildCustomInfo($hd, $custom);
  1147. // 最低消费数量:花材扎数 + 花束份数(与结算页「还差 N 扎」同源)
  1148. $unMeetBigNum = $itemBigNum;
  1149. foreach ($resolvedProduct as $row) {
  1150. if ((int)($row['property'] ?? 1) === 0) {
  1151. $unMeetBigNum = bcadd($unMeetBigNum, $row['num'] ?? 0, 2);
  1152. }
  1153. }
  1154. $additionalCosts = \bizHd\order\classes\PsMethodClass::calcFeeForMallContext(
  1155. $this->shopId,
  1156. $this->mainId,
  1157. $sendType,
  1158. $goodsOnlyPrice,
  1159. $unMeetBigNum,
  1160. $hdCustomId,
  1161. $customInfo
  1162. );
  1163. $unMeetSendCost = $additionalCosts['sendCost'] ?? 0;
  1164. $packingFee = $additionalCosts['packCost'] ?? 0;
  1165. $mapSet = ShopClass::hasIntraCity($this->shop);
  1166. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  1167. $hasItem = !empty($itemRows);
  1168. // 含花材(含混合)按花材报价 goodsType=1;纯花束按 0
  1169. $quoteGoodsType = $hasItem ? 1 : 0;
  1170. // 跑腿 style=2:按包运费花束 / 不包运费花束 / 纯花材满减 + 跑腿或自定义(异常兜底)
  1171. if (isset($post['sendType']) && (int)$post['sendType'] === 2) {
  1172. if ((int)$openIntraCity === 2) {
  1173. util::fail('不能使用跑腿');
  1174. }
  1175. if (empty($post['long']) || empty($post['lat'])) {
  1176. util::fail('位置错误');
  1177. }
  1178. $shopLat = $shop->lat ?? '';
  1179. $shopLong = $shop->long ?? '';
  1180. if (empty($shopLat) || empty($shopLong)) {
  1181. util::fail('商家门店地址定位未设置,编号263');
  1182. }
  1183. $psConfig = PsMethodClass::getConfig($this->shopId, $this->mainId, 2);
  1184. if (empty($psConfig) || (int)($psConfig['status'] ?? 0) !== 1) {
  1185. util::fail('跑腿配送方式未启用');
  1186. }
  1187. $freightMode = PsMethodClass::resolveMixRunnerFreightMode($resolvedProduct);
  1188. $calcType = (int)($psConfig['calcType'] ?? 0);
  1189. $quoteCustom = (object)[
  1190. 'name' => $post['receiveUserName'] ?? '',
  1191. 'mobile' => $post['receiveMobile'] ?? '',
  1192. 'fullAddress' => $post['address'] ?? ($post['fullAddress'] ?? ''),
  1193. 'floor' => $post['floor'] ?? '',
  1194. 'dist' => $post['dist'] ?? '',
  1195. 'lat' => $post['lat'],
  1196. 'long' => $post['long'],
  1197. 'address' => $post['address'] ?? '',
  1198. 'city' => $post['city'] ?? '',
  1199. ];
  1200. $distanceRespond = mapUtil::calcShopDistanceByEleBike($quoteCustom, $shop, 0);
  1201. $distanceMeters = (float)($distanceRespond['distance'] ?? 0);
  1202. $distanceKm = (float)($distanceRespond['distanceKm'] ?? 0);
  1203. if ($distanceMeters <= 0 && $distanceKm <= 0) {
  1204. util::fail('算运费失败,请完善收货地址');
  1205. }
  1206. if ($distanceMeters <= 0 && $distanceKm > 0) {
  1207. $distanceMeters = $distanceKm * 1000;
  1208. }
  1209. $sendCost = 0;
  1210. $freightSource = '';
  1211. if ($freightMode === 'bouquetIncluded') {
  1212. // A:含包运费花束 → hsFreeKm / hsPerKmPrice
  1213. $sendCost = PsMethodClass::calcBouquetFreightByDistance($psConfig, $distanceMeters);
  1214. $freightSource = 'bouquetIncluded';
  1215. } elseif ($freightMode === 'flowerOnly'
  1216. && PsMethodClass::matchReduceRuleFree($psConfig, $distanceMeters, $itemBigNum, $goodsOnlyPrice)) {
  1217. // C:纯花材命中满减 → 免跑腿
  1218. $sendCost = 0;
  1219. $freightSource = 'reduceFree';
  1220. } else {
  1221. // B 或不免满减的 C:按 calcType 跑腿或自定义;跑腿异常最终自定义兜底
  1222. if ($calcType === 1) {
  1223. try {
  1224. $sendCost = PsMethodClass::calcCustomFreightByDistance($psConfig, $distanceKm > 0 ? $distanceKm : ($distanceMeters / 1000));
  1225. $freightSource = 'custom';
  1226. } catch (\Exception $e) {
  1227. util::fail($e->getMessage());
  1228. }
  1229. } else {
  1230. $runnerOk = false;
  1231. if ((int)$openIntraCity === 1 && !empty($post['deliveryPlatform'])) {
  1232. $prefix = 'PT-MIX-' . $this->mainId . '-';
  1233. $orderSn = $prefix . round(microtime(true) * 1000);
  1234. $ghsInfo = ['mainId' => $this->mainId, 'shopId' => $this->shopId];
  1235. try {
  1236. $quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
  1237. 'productList' => $resolvedProduct,
  1238. 'deliveryPlatform' => $post['deliveryPlatform'],
  1239. 'deliveryBracketContent' => $post['deliveryBracketContent'] ?? '',
  1240. 'ghsInfo' => $ghsInfo,
  1241. 'custom' => $quoteCustom,
  1242. 'order' => [
  1243. 'orderSn' => $orderSn,
  1244. 'goodsType' => $quoteGoodsType,
  1245. 'itemTotalAmount' => $goodsOnlyPrice,
  1246. 'remark' => $post['remark'] ?? '',
  1247. ],
  1248. 'mainId' => $this->mainId,
  1249. 'productCount' => $totalNum,
  1250. 'shConfig' => $psConfig,
  1251. ]);
  1252. $sendCost = $quoteResult['sendCost'];
  1253. $distanceMeters = (float)($quoteResult['sendDistance'] ?? $distanceMeters);
  1254. $freightSource = 'platform';
  1255. $runnerOk = true;
  1256. } catch (\Exception $e) {
  1257. $runnerOk = false;
  1258. noticeUtil::push('商城混合单跑腿报价异常,改走自定义:' . $e->getMessage());
  1259. }
  1260. }
  1261. if (!$runnerOk) {
  1262. try {
  1263. $sendCost = PsMethodClass::calcCustomFreightByDistance(
  1264. $psConfig,
  1265. $distanceKm > 0 ? $distanceKm : ($distanceMeters / 1000)
  1266. );
  1267. $freightSource = 'customFallback';
  1268. } catch (\Exception $e) {
  1269. util::fail('跑腿计算异常且自定义计费不可用,请更换配送方式');
  1270. }
  1271. }
  1272. }
  1273. }
  1274. $post['sendCost'] = $sendCost;
  1275. $post['sendDistance'] = $distanceMeters;
  1276. $post['freightSource'] = $freightSource;
  1277. $modifyPrice = bcadd($modifyPrice, $sendCost, 2);
  1278. }
  1279. if ($unMeetSendCost > 0) {
  1280. $post['sendCost'] = bcadd($post['sendCost'] ?? 0, $unMeetSendCost, 2);
  1281. $modifyPrice = bcadd($modifyPrice, $unMeetSendCost, 2);
  1282. }
  1283. if ($packingFee > 0) {
  1284. $post['packingFee'] = $packingFee;
  1285. $modifyPrice = bcadd($modifyPrice, $packingFee, 2);
  1286. }
  1287. // 红包(归属花店客户,与 buy-item 一致)
  1288. $hbId = $post['hbId'] ?? 0;
  1289. $hb = null;
  1290. if ($hbId > 0) {
  1291. $hb = HbClass::getById($hbId, true);
  1292. if (!empty($hb)) {
  1293. if ($hb->customId != $hdCustomId) {
  1294. util::fail('不是你的红包');
  1295. }
  1296. if ($hb->amount != $post['hbAmount']) {
  1297. util::fail('红包金额不相等');
  1298. }
  1299. if ($hb->status == 1) {
  1300. util::fail('红包已使用');
  1301. }
  1302. if ($hb->status == -1) {
  1303. util::fail('红包已作废');
  1304. }
  1305. if ($hb->endTime < time()) {
  1306. $hb->status = -1;
  1307. $hb->save();
  1308. util::fail('红包已失效');
  1309. }
  1310. if ($hb->beginTime > time()) {
  1311. util::fail('红包可使用期未到');
  1312. }
  1313. // 混合结算:按适用范围用商品明细校验最低消费(不含运费包装费)
  1314. HbScopeClass::assertMinConsume($hb, $resolvedProduct ?? [], $goodsOnlyPrice ?? $modifyPrice);
  1315. $modifyPrice = bcsub($modifyPrice, $hb->amount, 2);
  1316. } else {
  1317. util::fail('红包无效');
  1318. }
  1319. }
  1320. $psMethodError = \bizHd\order\classes\PsMethodClass::checkLimit(
  1321. $this->shopId,
  1322. $this->mainId,
  1323. $sendType,
  1324. $goodsOnlyPrice,
  1325. $unMeetBigNum,
  1326. $packingFee,
  1327. $unMeetSendCost,
  1328. $hdCustomId,
  1329. $customInfo
  1330. );
  1331. if ($psMethodError !== '') {
  1332. util::fail($psMethodError);
  1333. }
  1334. // 商家配送(0)/跑腿(2)必填配送时间;到店自取(1)、物流(3)、快递(4)不强制(后两者由客服确认时效)
  1335. $sendType = intval($post['sendType'] ?? 0);
  1336. if (in_array($sendType, [0, 2], true)) {
  1337. if (empty($post['reachPeriod'])) {
  1338. util::fail('请选择配送时间哈');
  1339. }
  1340. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  1341. } elseif (!empty($post['reachPeriod'])) {
  1342. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  1343. }
  1344. $post['bigNum'] = $totalNum;
  1345. $post['modifyPrice'] = $modifyPrice;
  1346. $post['hasSeckill'] = $hasSeckillGoods ? 1 : 0;
  1347. $post['seckillGoodsPrice'] = $seckillGoodsPrice;
  1348. $post['seckillGoodsNum'] = $seckillGoodsNum;
  1349. // 互斥比较与落单使用同一口径:秒杀活动价不参与会员折和门店满减
  1350. $wholeDiscountPrice = bcsub(
  1351. $modifyPrice,
  1352. HdOrderClass::capSeckillExcludePrice($seckillGoodsPrice, $modifyPrice),
  1353. 2
  1354. );
  1355. $wholeDiscountNum = bcsub($unMeetBigNum, $seckillGoodsNum, 2);
  1356. if (bccomp($wholeDiscountNum, '0', 2) < 0) {
  1357. $wholeDiscountNum = 0;
  1358. }
  1359. $wholePick = WholeOrderDiscountClass::pick(
  1360. $wholeDiscountPrice,
  1361. $wholeDiscountNum,
  1362. $custom->discount ?? 1,
  1363. $shop
  1364. );
  1365. if ($wholePick['type'] === WholeOrderDiscountClass::TYPE_MEMBER) {
  1366. $post['skipShopMeetCut'] = 1;
  1367. } elseif ($wholePick['type'] === WholeOrderDiscountClass::TYPE_SHOP) {
  1368. $post['skipMemberDiscount'] = 1;
  1369. }
  1370. $return = \bizHd\order\services\OrderService::createHdOrder($post, $custom, $hasPay);
  1371. $orderSn = $return->orderSn ?? '';
  1372. if (!empty($orderSn) && (float)$unMeetSendCost > 0) {
  1373. $unMeetSendKey = 'hd_order_unmeet_send:' . $orderSn;
  1374. Yii::$app->redis->executeCommand('SETEX', [$unMeetSendKey, 864000, (string)$unMeetSendCost]);
  1375. }
  1376. if (!empty($hb)) {
  1377. $hb->status = 1;
  1378. $hb->orderId = $return->id;
  1379. $hb->save();
  1380. }
  1381. if ($return->sendType == 2) {
  1382. $ext = ShopExtClass::getByCondition(['shopId' => $return->shopId], true, null, 'id,shopId,thirdSend');
  1383. if (!empty($ext) && $ext->thirdSend == 1) {
  1384. util::fail('本店暂不能使用跑腿呢');
  1385. }
  1386. }
  1387. $transaction->commit();
  1388. $transactionFinished = true;
  1389. \bizHd\product\classes\ProductClass::clearLimitBuyRollbackSnapshot();
  1390. HomePageModuleClass::clearSeckillReservationSnapshot();
  1391. $orderSn = $return->orderSn ?? '';
  1392. // 优先 actPrice:门店满减落在 actPrice/orderPrice,避免仍按未减金额去支付
  1393. $orderPrice = $return->actPrice ?? ($return->orderPrice ?? 0);
  1394. $id = $return->id ?? 0;
  1395. $getPayType = dict::getDict('getPayType');
  1396. util::success([
  1397. 'orderSn' => $orderSn,
  1398. 'totalPrice' => $orderPrice,
  1399. 'couponId' => 0,
  1400. 'id' => $id,
  1401. 'getPayType' => $getPayType,
  1402. ]);
  1403. } catch (\Exception $e) {
  1404. $transaction->rollBack();
  1405. \bizHd\product\classes\ProductClass::rollbackLimitBuySnapshot();
  1406. HomePageModuleClass::rollbackSeckillReservationSnapshot();
  1407. $transactionFinished = true;
  1408. Yii::error("合并下单失败:" . $e->getMessage());
  1409. util::fail('下单失败');
  1410. }
  1411. }
  1412. //下单要用到的相关信息 ssh 2019.12.6
  1413. public function actionOrderRelate()
  1414. {
  1415. $regionTree = RegionService::tree();
  1416. //门店名称
  1417. $shop = !empty($this->shop) ? $this->shop->attributes : [];
  1418. $sjName = $shop['merchantName'] ?? '';
  1419. $shopName = $shop['shopName'] ?? '';
  1420. $shop['showName'] = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  1421. $avatar = $shop['avatar'] ?? '';
  1422. $smallAvatar = imgUtil::groupImg($avatar) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
  1423. $shop['smallAvatar'] = $smallAvatar;
  1424. $freight = ['first' => 5, 'add' => 2];
  1425. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  1426. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  1427. util::success($out);
  1428. }
  1429. //余额支付 ssh 20250410
  1430. public function actionBalancePay()
  1431. {
  1432. $orderSn = Yii::$app->request->post('orderSn');
  1433. if (empty($orderSn)) {
  1434. util::fail('订单编号缺失');
  1435. }
  1436. //避免重复提交
  1437. util::checkRepeatCommit($orderSn, 5);
  1438. $connection = Yii::$app->db;
  1439. $transaction = $connection->beginTransaction();
  1440. try {
  1441. $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';
  1442. $order = OrderClass::getByCondition(['orderSn' => $orderSn], true, null, $fields);
  1443. if (empty($order)) {
  1444. util::fail('没有找到订单');
  1445. }
  1446. if ($order->shopId != $this->shopId) {
  1447. util::fail('不是你的订单');
  1448. }
  1449. //支付前验证订单有效性
  1450. OrderService::checkBeforePay($order);
  1451. $payWay = dict::getDict('payWay', 'balancePay');
  1452. \bizHd\order\classes\OrderClass::payAfter($order, $payWay);
  1453. $transaction->commit();
  1454. //解决重复通知,重要
  1455. $cacheKey = 'mall_order_balance_pay_' . $orderSn;
  1456. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1457. if (empty($has)) {
  1458. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 864000, 'has']);
  1459. //打印小票和语音播报
  1460. $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';
  1461. $order = \bizHd\order\classes\OrderClass::getByCondition(['orderSn' => $orderSn], true, null, $fields);
  1462. if (!empty($order)) {
  1463. \bizHd\order\classes\OrderClass::onlinePrint($order);
  1464. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  1465. HdDeliveryOrderClass::payAfter($order);
  1466. $shopId = $order->shopId ?? 0;
  1467. $shop = ShopClass::getById($shopId, true);
  1468. if (in_array($order->fromType, [1, 3])) {
  1469. //您有新的收入提醒
  1470. WxMessageClass::gatheringIncomeInform($shop, $order);
  1471. }
  1472. if ($order->fromType == 2) {
  1473. //来自商城的新订单微信通知
  1474. WxMessageClass::hdNewOrderInform($shop, $order);
  1475. }
  1476. }
  1477. }
  1478. util::complete('支付成功');
  1479. } catch (\Exception $e) {
  1480. $transaction->rollBack();
  1481. Yii::error("支付原因:" . $e->getMessage());
  1482. util::fail('支付失败');
  1483. }
  1484. }
  1485. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  1486. public function actionWxPay()
  1487. {
  1488. ini_set('date.timezone', 'Asia/Shanghai');
  1489. $post = Yii::$app->request->post();
  1490. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1491. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1492. $order = OrderService::getByOrderSn($orderSn);
  1493. if (empty($order)) {
  1494. util::fail('订单号无效');
  1495. }
  1496. $orderId = $order['id'];
  1497. //验证优惠券是否还有效
  1498. if (!empty($couponId)) {
  1499. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  1500. }
  1501. //支付前验证订单有效性
  1502. OrderService::checkBeforePay($order);
  1503. $name = !empty($order['orderName']) ? $order['orderName'] : '购买花材';
  1504. $shop = $this->shop;
  1505. if (empty($shop)) {
  1506. util::fail('没有找到门店信息');
  1507. }
  1508. if (isset($shop->shopName) && !empty($shop->shopName)) {
  1509. $name .= '(' . $shop->shopName . ')';
  1510. }
  1511. $totalFee = $order['mainPay'];
  1512. $openId = '';
  1513. if (!empty($post['miniOpenId'])) {
  1514. $openId = $post['miniOpenId'];
  1515. //noticeUtil::push('散客买花时,通过前端获取了openId:' . $openId, '15280215347');
  1516. }
  1517. if (empty($openId)) {
  1518. if (isset($this->user['miniOpenId']) && !empty($this->user['miniOpenId'])) {
  1519. $openId = $this->user['miniOpenId'];
  1520. //noticeUtil::push('散客买花时,通过数据库获取了openId:' . $openId, '15280215347');
  1521. }
  1522. }
  1523. if (empty($openId)) {
  1524. util::fail('没有找到openId');
  1525. }
  1526. $now = time();
  1527. $expireTime = $now + 1800;
  1528. $updateData = [];
  1529. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1530. $oldOrderSn = $orderSn;
  1531. //老单号需要关单,否则有付款成功的风险,老单号关闭成功了,才能生成新单号
  1532. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1533. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1534. $params = [
  1535. 'appid' => 'OP00002119',
  1536. 'serial_no' => '018b08cfddbd',
  1537. 'merchant_no' => $shop->lklSjNo,
  1538. 'term_no' => $shop->lklScanTermNo,
  1539. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1540. 'lklCertificatePath' => $lklCertificatePath,
  1541. ];
  1542. $laResource = new Lakala($params);
  1543. $closeParams = [
  1544. 'orderSn' => $oldOrderSn,
  1545. ];
  1546. $response = $laResource->close($closeParams);
  1547. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1548. $msg = $response['msg'] ?? '';
  1549. $lklSjNo = $shop->lklSjNo ?? '';
  1550. noticeUtil::push('重点注意,散客买花更换单号没有成功,单号:' . $oldOrderSn . ',关单没有成功,' . $msg . '。商户号:' . $lklSjNo, '15280215347');
  1551. util::fail('出错了哦,请重新下一单');
  1552. }
  1553. $orderSn = orderSn::getOrderSn();
  1554. $updateData['orderSn'] = $orderSn;
  1555. OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
  1556. } else {
  1557. //已请求的不能再修改价格
  1558. $updateData['modPrice'] = 0;
  1559. }
  1560. if (empty($order['deadline'])) {
  1561. $updateData['deadline'] = $expireTime;
  1562. }
  1563. if (!empty($updateData)) {
  1564. OrderService::updateById($orderId, $updateData);
  1565. }
  1566. if (bccomp((string)$totalFee, '0', 2) == 1) {
  1567. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1568. $sjExtend = WxOpenClass::getMallWxInfo();
  1569. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1570. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1571. $params = [
  1572. 'appid' => 'OP00002119',
  1573. 'serial_no' => '018b08cfddbd',
  1574. 'merchant_no' => $shop->lklSjNo,
  1575. 'term_no' => $shop->lklScanTermNo,
  1576. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1577. 'lklCertificatePath' => $lklCertificatePath,
  1578. ];
  1579. $laResource = new Lakala($params);
  1580. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  1581. $wxParams = [
  1582. 'orderSn' => $orderSn,
  1583. 'amount' => $totalFee,
  1584. 'capitalType' => $capitalType,
  1585. 'notifyUrl' => $notifyUrl,
  1586. 'wxAppId' => $sjExtend['miniAppId'],
  1587. 'openId' => $openId,
  1588. 'subject' => $name,
  1589. 'couponId' => $couponId,
  1590. ];
  1591. $response = $laResource->driveWxPay($wxParams);
  1592. if(!isset($response['code']) || $response['code'] != 'BBS00000') {
  1593. $errMsg = $response['msg'] ?? '';
  1594. noticeUtil::push($errMsg, '15280215347');
  1595. util::fail('支付失败');
  1596. }
  1597. } else if (bccomp((string)$totalFee, '0.00', 2) == 0){
  1598. Yii::info('付款金额为0');
  1599. $connection = Yii::$app->db;
  1600. $transaction = $connection->beginTransaction();
  1601. try {
  1602. OrderClass::completeZeroAmountPay($orderId);
  1603. $transaction->commit();
  1604. } catch (\Exception $e) {
  1605. $transaction->rollBack();
  1606. Yii::error('零元订单支付后续失败:' . $e->getMessage());
  1607. util::fail('支付失败');
  1608. }
  1609. $cacheKey = 'mall_order_zero_pay_' . $orderSn;
  1610. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  1611. if (empty($has)) {
  1612. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 864000, 'has']);
  1613. $paidOrder = HdOrderClass::getByCondition(['orderSn' => $orderSn], true);
  1614. if (!empty($paidOrder)) {
  1615. HdOrderClass::onlinePrint($paidOrder);
  1616. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  1617. HdDeliveryOrderClass::payAfter($paidOrder);
  1618. $shopId = $paidOrder->shopId ?? 0;
  1619. $shop = ShopClass::getById($shopId, true);
  1620. $shopExt = \biz\shop\classes\ShopExtClass::getByCondition(['shopId' => $shopId], true);
  1621. if (!empty($shopExt) && $shopExt->needWork == 1 && $paidOrder->hasWork != 1 && !empty($shop)) {
  1622. $mainId = $shop->mainId ?? 0;
  1623. $main = \bizHd\shop\classes\MainClass::getById($mainId, true);
  1624. \bizHd\work\classes\WorkClass::needWork($paidOrder, $main);
  1625. $hasWork = \bizHd\work\classes\WorkClass::getByCondition(['orderId' => $orderId], true);
  1626. if (!empty($hasWork)) {
  1627. $paidOrder->hasWork = 1;
  1628. $paidOrder->save();
  1629. }
  1630. \biz\shop\classes\ShopExtClass::newWorkRemind($shopExt, $paidOrder);
  1631. }
  1632. if (!empty($shop)) {
  1633. WxMessageClass::hdNewOrderInform($shop, $paidOrder);
  1634. }
  1635. }
  1636. }
  1637. $new = [
  1638. 'id' => $orderId,
  1639. 'orderSn' => $orderSn,
  1640. ];
  1641. util::error(errCode::ORDER_PAY_AMOUNT_ZERO, '付款金额为0', $new);
  1642. } else {
  1643. util::fail('付款金额不能为负数');
  1644. }
  1645. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  1646. $appId = $newParams['app_id'] ?? '';
  1647. $nonceStr = $newParams['nonce_str'] ?? '';
  1648. $paySign = $newParams['pay_sign'] ?? '';
  1649. $package = $newParams['package'] ?? '';
  1650. $signType = $newParams['sign_type'] ?? '';
  1651. $timeStamp = $newParams['time_stamp'] ?? '';
  1652. $new = [
  1653. 'id' => $orderId,
  1654. 'appId' => $appId,
  1655. 'nonceStr' => $nonceStr,
  1656. 'paySign' => $paySign,
  1657. 'package' => $package,
  1658. 'signType' => $signType,
  1659. 'timeStamp' => $timeStamp,
  1660. 'orderSn' => $orderSn,
  1661. ];
  1662. util::success($new);
  1663. }
  1664. //快捷付款订单
  1665. public function actionFastPay()
  1666. {
  1667. ini_set('date.timezone', 'Asia/Shanghai');
  1668. $post = Yii::$app->request->post();
  1669. $payWay = $post['payWay'] ?? 0;
  1670. $shopId = $this->shopId;
  1671. $shop = $this->shop;
  1672. if (empty($shop)) {
  1673. util::fail('没有门店信息');
  1674. }
  1675. $customId = $this->customId;
  1676. $custom = $this->custom;
  1677. $hdId = $this->hdId;
  1678. $hd = $this->hd;
  1679. if (empty($customId) || empty($hdId)) {
  1680. //考虑没有登录时的付款
  1681. $defaultCustomId = $shop->defaultCustomId ?? 0;
  1682. if (empty($defaultCustomId)) {
  1683. util::fail('请设置快捷开单的客户');
  1684. }
  1685. $customId = $defaultCustomId;
  1686. $custom = CustomClass::getById($defaultCustomId, true);
  1687. if (empty($custom)) {
  1688. util::fail('无效的快捷客户');
  1689. }
  1690. $hdId = $custom->hdId;
  1691. $hd = \bizMall\hd\classes\HdClass::getById($hdId, true);
  1692. if (empty($hd)) {
  1693. util::fail('没有花店信息呢!');
  1694. }
  1695. }
  1696. $post['hdId'] = $hdId;
  1697. $post['hdName'] = $hd->name ?? '';
  1698. $customName = $custom->name ?? '';
  1699. $customPy = $custom->py ?? '';
  1700. $post['customName'] = $customName;
  1701. $post['customNamePy'] = $customPy;
  1702. $post['shopId'] = $shopId;
  1703. $post['mainId'] = $this->mainId;
  1704. $post['customId'] = $customId;
  1705. $prePrice = round($post['prePrice'], 2);
  1706. $actPrice = $prePrice;
  1707. if ($actPrice <= 0) {
  1708. util::fail('请填写付款金额');
  1709. }
  1710. $post['actPrice'] = $actPrice;
  1711. $post['userId'] = $this->userId;
  1712. $now = time();
  1713. $expireTime = $now + 300;//订单5分钟后过期
  1714. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1715. $post['deadline'] = date("Y-m-d H:i:s", $expireTime);
  1716. $order = ScanPayClass::addOrder($post);
  1717. $orderId = $order->id ?? 0;
  1718. $orderSn = $order->orderSn ?? '';
  1719. $capitalType = dict::getDict('capitalType', 'scanPay', 'id');
  1720. if ($payWay == 0) {
  1721. //微信
  1722. $name = '购买鲜花,扫码付款';
  1723. $totalFee = $actPrice;
  1724. $user = UserService::getById($this->userId);
  1725. //小程序使用miniOpenId
  1726. $openId = $user['miniOpenId'];
  1727. if (empty($openId)) {
  1728. $openId = !empty($post['miniOpenId']) ? $post['miniOpenId'] : '';
  1729. }
  1730. if (empty($openId)) {
  1731. util::fail('没有微信信息');
  1732. }
  1733. $sjExtend = WxOpenClass::getMallWxInfo();
  1734. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1735. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1736. $params = [
  1737. 'appid' => 'OP00002119',
  1738. 'serial_no' => '018b08cfddbd',
  1739. 'merchant_no' => $shop->lklSjNo,
  1740. 'term_no' => $shop->lklScanTermNo,
  1741. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1742. 'lklCertificatePath' => $lklCertificatePath,
  1743. ];
  1744. $laResource = new Lakala($params);
  1745. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  1746. $wxParams = [
  1747. 'orderSn' => $orderSn,
  1748. 'amount' => $totalFee,
  1749. 'capitalType' => $capitalType,
  1750. 'notifyUrl' => $notifyUrl,
  1751. 'wxAppId' => $sjExtend['miniAppId'],
  1752. 'openId' => $openId,
  1753. 'subject' => $name,
  1754. 'couponId' => 0,
  1755. ];
  1756. $response = $laResource->driveWxPay($wxParams);
  1757. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1758. $errMsg = $response['msg'] ?? '';
  1759. noticeUtil::push($errMsg, '15280215347');
  1760. util::fail('支付失败');
  1761. }
  1762. $newParams = $response['resp_data']['acc_resp_fields'] ?? [];
  1763. $appId = $newParams['app_id'] ?? '';
  1764. $nonceStr = $newParams['nonce_str'] ?? '';
  1765. $paySign = $newParams['pay_sign'] ?? '';
  1766. $package = $newParams['package'] ?? '';
  1767. $signType = $newParams['sign_type'] ?? '';
  1768. $timeStamp = $newParams['time_stamp'] ?? '';
  1769. $new = [
  1770. 'id' => $orderId,
  1771. 'appId' => $appId,
  1772. 'nonceStr' => $nonceStr,
  1773. 'paySign' => $paySign,
  1774. 'package' => $package,
  1775. 'signType' => $signType,
  1776. 'timeStamp' => $timeStamp,
  1777. 'orderSn' => $orderSn,
  1778. ];
  1779. util::success($new);
  1780. } elseif ($payWay == 1) {
  1781. //支付宝
  1782. $totalFee = $actPrice;
  1783. $subject = '购买鲜花,扫码付款';
  1784. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1785. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1786. $params = [
  1787. 'appid' => 'OP00002119',
  1788. 'serial_no' => '018b08cfddbd',
  1789. 'merchant_no' => $shop->lklSjNo,
  1790. 'term_no' => $shop->lklB2BTermNo,
  1791. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1792. 'lklCertificatePath' => $lklCertificatePath,
  1793. ];
  1794. $laResource = new Lakala($params);
  1795. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/cash-pay-callback";
  1796. $cashParams = [
  1797. 'orderSn' => $orderSn,
  1798. 'amount' => $totalFee,
  1799. 'capitalType' => $capitalType,
  1800. 'notifyUrl' => $notifyUrl,
  1801. 'subject' => $subject,
  1802. ];
  1803. $response = $laResource->cashierPay($cashParams);
  1804. if (!isset($response['code']) || $response['code'] != '000000') {
  1805. util::fail('支付失败了');
  1806. }
  1807. $url = $response['resp_data']['counter_url'] ?? '';
  1808. if (empty($url)) {
  1809. util::fail('支付失败');
  1810. }
  1811. util::success(['url' => $url]);
  1812. } elseif ($payWay == 2) {
  1813. //余额支付
  1814. util::fail('暂不支持');
  1815. } else {
  1816. util::fail('无效的支付方式');
  1817. }
  1818. }
  1819. //订单列表 ssh 2019.12.12
  1820. public function actionList()
  1821. {
  1822. $get = Yii::$app->request->get();
  1823. $status = $get['status'] ?? 0;
  1824. $hdId = $get['hdId'] ?? 0;
  1825. $userId = $this->userId;
  1826. $where = ['userId' => $userId];
  1827. if (!empty($status)) {
  1828. $where['status'] = $status;
  1829. }
  1830. if (!empty($hdId)) {
  1831. $hd = \bizMall\hd\classes\HdClass::getById($hdId, true);
  1832. if (empty($hd)) {
  1833. util::fail('无效的花店');
  1834. }
  1835. if ($hd['userId'] != $userId) {
  1836. util::fail('不是你的花店');
  1837. }
  1838. $where['hdId'] = $hdId;
  1839. }
  1840. $list = OrderService::getOrderList($where);
  1841. util::success($list);
  1842. }
  1843. //订单评价
  1844. public function actionComment()
  1845. {
  1846. $post = Yii::$app->request->post();
  1847. $id = $post['id'];
  1848. $order = OrderClass::getById($id);
  1849. if ($order['grade'] > 0) {
  1850. util::fail('您已经评过了');
  1851. }
  1852. OrderService::comment($post);
  1853. util::complete('提交成功');
  1854. }
  1855. // 订单详情:含 canApplyRefund / refundApplyId,供底部申请售后、查看申请
  1856. public function actionDetail()
  1857. {
  1858. $id = Yii::$app->request->get('id', 0);
  1859. $detail = OrderClass::getOrderById($id);
  1860. $userId = $this->userId;
  1861. if ($detail['userId'] != $userId) {
  1862. util::fail('不是你的单,不能查看');
  1863. }
  1864. $shOrderMap = [];
  1865. if ($detail['hasForward'] == 1) {
  1866. $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
  1867. }
  1868. $detail['shOrderMap'] = $shOrderMap;
  1869. //是否显示余额支付按钮 ssh 20260120
  1870. $hd = $this->hd;
  1871. $balance = $hd->balance ?? 0;
  1872. $showYePay = $balance > 0 ? 1 : 0;
  1873. $detail['showYePay'] = $showYePay;
  1874. $detail['balance'] = $balance;
  1875. $detail['rechargeWeal'] = $this->shop->rechargeWeal; //是否开启余额支付
  1876. // 与 RefundController::canApplyRefund 对齐;最新申请供详情页「查看申请」入口
  1877. $detail['distOrderSettled'] = DistributionOrderClass::isDistOrderSettled((int)$id) ? 1 : 0;
  1878. $apply = HdRefundClass::getLatestByOrderId((int)$id);
  1879. $detail['canApplyRefund'] = $this->canApplyRefundForDetail($detail, $apply) ? 1 : 0;
  1880. $detail['refundApplyId'] = 0;
  1881. $detail['refundApplyStatus'] = '';
  1882. $detail['refundApplyStatusText'] = '';
  1883. // 有顾客申请才给入口;商家即时售后 userId=0 不展示「查看申请」
  1884. if (!empty($apply) && !empty($apply['id'])) {
  1885. $detail['refundApplyId'] = (int)$apply['id'];
  1886. $detail['refundApplyStatus'] = (int)($apply['status'] ?? 0);
  1887. $detail['refundApplyStatusText'] = HdRefundMallClass::statusText($apply['status'] ?? 0);
  1888. }
  1889. // 配送方式名称:xhPsMethod.name(style = 订单 sendType)
  1890. $detail['psMethodName'] = $this->resolvePsMethodName($detail);
  1891. util::success($detail);
  1892. }
  1893. /**
  1894. * 解析订单配送方式名称(xhPsMethod.name,无记录时回退字典默认名)
  1895. * @param array $order 订单详情
  1896. * @return string
  1897. */
  1898. protected function resolvePsMethodName($order)
  1899. {
  1900. $mainId = (int)($order['mainId'] ?? 0);
  1901. $style = (int)($order['sendType'] ?? 0);
  1902. if ($mainId > 0) {
  1903. $psMethod = PsMethodClass::getByCondition([
  1904. 'mainId' => $mainId,
  1905. 'style' => $style,
  1906. ]);
  1907. if (!empty($psMethod['name'])) {
  1908. return (string)$psMethod['name'];
  1909. }
  1910. }
  1911. $default = dict::getDict('shMethod', $style);
  1912. return (string)($default['name'] ?? '');
  1913. }
  1914. /**
  1915. * 订单详情是否可申请售后(与 mall RefundController::canApplyRefund 规则一致)
  1916. * @param array $order 订单详情
  1917. * @param array|null $apply 最新顾客申请,避免详情里重复查
  1918. * @return bool
  1919. */
  1920. protected function canApplyRefundForDetail($order, $apply = null)
  1921. {
  1922. if ((int)($order['payStatus'] ?? 0) !== 1) {
  1923. return false;
  1924. }
  1925. $status = (int)($order['status'] ?? 0);
  1926. if (in_array($status, [HdOrderClass::ORDER_STATUS_UN_PAY, HdOrderClass::ORDER_STATUS_CANCEL, 6], true)) {
  1927. return false;
  1928. }
  1929. if ((int)($order['forward'] ?? 0) === 1) {
  1930. return false;
  1931. }
  1932. if ($apply === null) {
  1933. $apply = HdRefundClass::getLatestByOrderId((int)($order['id'] ?? 0));
  1934. }
  1935. if (!empty($apply) && (int)($apply['status'] ?? -1) === HdRefundClass::STATUS_PENDING) {
  1936. return false;
  1937. }
  1938. if (DistributionOrderClass::isDistOrderSettled((int)($order['id'] ?? 0))) {
  1939. return false;
  1940. }
  1941. $could = bcsub((string)($order['orderPrice'] ?? 0), (string)($order['tkPrice'] ?? 0), 2);
  1942. if (bccomp($could, '0', 2) <= 0) {
  1943. return false;
  1944. }
  1945. return true;
  1946. }
  1947. //获取详情 ssh 20220512
  1948. public function actionInfo()
  1949. {
  1950. $sn = Yii::$app->request->get('orderSn', '');
  1951. $detail = OrderClass::getOrderBySn($sn);
  1952. util::success($detail);
  1953. }
  1954. }