OrderController.php 83 KB

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