OrderController.php 86 KB

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