OrderController.php 83 KB

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