OrderController.php 85 KB

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