OrderController.php 99 KB

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