GroupBuyController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. <?php
  2. namespace mall\controllers;
  3. use bizHd\custom\classes\CustomClass;
  4. use bizHd\goods\classes\GoodsClass;
  5. use bizHd\groupBuy\classes\GroupBuyActivityClass;
  6. use bizHd\groupBuy\classes\GroupBuyClass;
  7. use bizHd\groupBuy\classes\GroupBuyMemberClass;
  8. use bizHd\order\classes\PsMethodClass;
  9. use bizHd\order\services\OrderService;
  10. use bizHd\shop\classes\ShopClass;
  11. use bizMall\hd\classes\HdClass;
  12. use bizMall\pictext\classes\PicTextGoodsClass;
  13. use common\components\business;
  14. use common\components\dict;
  15. use common\components\orderSn;
  16. use common\components\stringUtil;
  17. use common\components\util;
  18. use mall\models\groupBuy\CreateGroupBuyForm;
  19. use mall\models\groupBuy\JoinGroupBuyForm;
  20. use Yii;
  21. /**
  22. * 商城端拼团接口
  23. * 落地页 / 团详情 / 开团 / 参团 / 我的拼团
  24. * 开团/参团订单按团购价结算,不叠加会员折扣、门店满减、红包
  25. * 配送附加费与跑腿距离运费与混合结算同源(PsMethodClass::calcFeeForMallContext / calcMixRunnerFreight)
  26. */
  27. class GroupBuyController extends BaseController
  28. {
  29. public $guestAccess = [
  30. 'goods-landing',
  31. 'detail',
  32. ];
  33. /**
  34. * 团购商品落地页:活动商品信息 + 商品详情图文 + 当前最快成团开放团
  35. * GET goodsId
  36. * 返回字段与商品详情页对齐:picTextGoods(标题/content JSON)供前端 rich-media-viewer 渲染
  37. */
  38. public function actionGoodsLanding()
  39. {
  40. $mainId = intval($this->mainId);
  41. if ($mainId <= 0) {
  42. util::fail('无效门店');
  43. }
  44. $goodsId = intval(Yii::$app->request->get('goodsId', 0));
  45. if ($goodsId <= 0) {
  46. util::fail('请选择商品');
  47. }
  48. $row = GroupBuyActivityClass::requireActiveGoodsRowByGoodsId($mainId, intval($this->shopId), $goodsId);
  49. $goods = GoodsClass::getById($goodsId, true);
  50. $cover = strval($row['cover'] ?? '');
  51. $coverUrl = $cover;
  52. if ($cover !== '' && strpos($cover, 'http') !== 0) {
  53. $formatted = business::formatUploadImg($cover);
  54. $coverUrl = $formatted['url'] ?? $cover;
  55. }
  56. // 轮播图兜底:保留商品图集;详情正文以 picTextGoods 为准(与 GoodsController::actionDetail 一致)
  57. $detailImages = [];
  58. $picTextGoods = [];
  59. if (!empty($goods)) {
  60. $pics = $goods->detail ?? ($goods->pic ?? '');
  61. if (is_string($pics) && $pics !== '') {
  62. $decoded = json_decode($pics, true);
  63. if (is_array($decoded)) {
  64. foreach ($decoded as $p) {
  65. if (is_string($p) && $p !== '') {
  66. if (strpos($p, 'http') === 0) {
  67. $detailImages[] = $p;
  68. } else {
  69. $fmt = business::formatUploadImg($p);
  70. $detailImages[] = $fmt['url'] ?? $p;
  71. }
  72. }
  73. }
  74. }
  75. }
  76. // 规格商品详情图文挂在主商品上,与商品详情接口取值规则一致
  77. $picTextGoodsId = empty($goods->masterId) ? $goodsId : intval($goods->masterId);
  78. $picTextRow = PicTextGoodsClass::getByCondition([
  79. 'mainId' => $mainId,
  80. 'goodsId' => $picTextGoodsId,
  81. ], true);
  82. if (!empty($picTextRow)) {
  83. $picTextGoods = $picTextRow;
  84. }
  85. }
  86. $openGroup = GroupBuyClass::getHottestOpenGroup(
  87. $mainId,
  88. $goodsId,
  89. intval($row['activityGoodsId'] ?? 0)
  90. );
  91. util::success([
  92. 'activityGoodsId' => intval($row['activityGoodsId']),
  93. 'activityId' => intval($row['activityId']),
  94. 'goodsId' => $goodsId,
  95. 'name' => strval($row['name']),
  96. 'cover' => $cover,
  97. 'coverUrl' => $coverUrl,
  98. 'price' => floatval($row['price']),
  99. 'originPrice' => floatval($row['originPrice']),
  100. 'groupSize' => intval($row['groupSize']),
  101. 'stock' => intval($row['stock']),
  102. 'limit' => intval($row['limit']),
  103. 'virtualGroup' => intval($row['virtualGroup']),
  104. 'virtualMinutes' => intval($row['virtualMinutes']),
  105. 'autoRefund' => 1,
  106. 'startTime' => intval($row['startTime']),
  107. 'endTime' => intval($row['endTime']),
  108. 'title' => strval($row['title']),
  109. 'subtitle' => strval($row['subtitle']),
  110. 'desc' => strval($row['desc']),
  111. 'showCountdown' => intval($row['showCountdown']),
  112. 'detailImages' => $detailImages,
  113. 'picTextGoods' => $picTextGoods,
  114. // 花束是否包运费:结算页跑腿模式(bouquetIncluded)与混合单同源判断
  115. 'freightType' => !empty($goods) ? intval($goods->freightType ?? 0) : 0,
  116. 'openGroup' => $openGroup,
  117. ]);
  118. }
  119. /**
  120. * 拼团详情
  121. * GET id
  122. */
  123. public function actionDetail()
  124. {
  125. $mainId = intval($this->mainId);
  126. if ($mainId <= 0) {
  127. util::fail('无效门店');
  128. }
  129. $id = intval(Yii::$app->request->get('id', 0));
  130. if ($id <= 0) {
  131. util::fail('请选择拼团');
  132. }
  133. $detail = GroupBuyClass::getDetail($mainId, $id);
  134. // 附带活动商品落地信息,便于分享进入后完整展示
  135. $landing = GroupBuyActivityClass::getActiveGoodsRowById($mainId, intval($this->shopId), intval($detail['activityGoodsId']));
  136. if (empty($landing)) {
  137. $landing = GroupBuyActivityClass::getActiveGoodsRowByGoodsId($mainId, intval($this->shopId), intval($detail['goodsId']));
  138. }
  139. if (!empty($landing) && !isset($landing['freightType'])) {
  140. $landingGoodsId = intval($landing['goodsId'] ?? ($detail['goodsId'] ?? 0));
  141. $landingGoods = $landingGoodsId > 0 ? GoodsClass::getById($landingGoodsId, true) : null;
  142. // 分享进详情也要带包运费标记,否则结算页跑腿会误走平台报价
  143. $landing['freightType'] = !empty($landingGoods) ? intval($landingGoods->freightType ?? 0) : 0;
  144. }
  145. $detail['activityGoods'] = $landing;
  146. $currentShopId = intval(Yii::$app->request->get('account', 0));
  147. $hd = HdClass::getByCondition(['shopId' => $currentShopId, 'userId' => $this->userId], false, null, 'id, customId');
  148. if (empty($hd)) {
  149. // util::error(errCode::GROUP_BUY_HD_NOT_BOUND, '客户暂无关联此店');
  150. // 客户与当前门店无关系时,立即建立
  151. if (empty($this->user)) {
  152. util::fail('请先登录');
  153. }
  154. $shop = ShopClass::getById($currentShopId, true);
  155. if (empty($shop)) {
  156. util::fail('门店不存在');
  157. }
  158. $respond = CustomClass::buildRelation($shop, $this->user);
  159. if (empty($respond) || empty($respond['hd'])) {
  160. util::fail('关联门店失败');
  161. }
  162. $hdId = intval($respond['hd']->id);
  163. } else {
  164. $hdId = intval($hd['id']);
  165. }
  166. $detail['hdId'] = $hdId;
  167. util::success($detail);
  168. }
  169. /**
  170. * 我要开团:创建团 + 创建待支付订单 + 挂接团长成员
  171. */
  172. public function actionCreate()
  173. {
  174. $form = new CreateGroupBuyForm();
  175. $form->loadAndValidate();
  176. $mainId = intval($this->mainId);
  177. $custom = $this->custom;
  178. if (empty($custom)) {
  179. util::fail('请先登录');
  180. }
  181. $customId = intval($custom->id);
  182. $activityGoodsId = intval($form->activityGoodsId);
  183. $goodsNum = max(1, intval($form->goodsNum));
  184. $row = GroupBuyActivityClass::requireActiveGoodsRowById($mainId, intval($this->shopId), $activityGoodsId);
  185. GroupBuyClass::assertPurchaseLimit($mainId, $customId, $row, $goodsNum);
  186. $connection = Yii::$app->db;
  187. $transaction = $connection->beginTransaction();
  188. try {
  189. $group = GroupBuyClass::createGroup($mainId, intval($this->shopId), $customId, $row);
  190. $groupBuyId = intval($group['id']);
  191. $order = $this->createGroupBuyOrder($form, $row, $groupBuyId, $goodsNum);
  192. GroupBuyMemberClass::bindOrderMember(
  193. $groupBuyId,
  194. $mainId,
  195. intval($this->shopId),
  196. $customId,
  197. intval($order->id),
  198. strval($order->orderSn),
  199. GroupBuyMemberClass::ROLE_LEADER
  200. );
  201. $transaction->commit();
  202. util::success([
  203. 'groupBuyId' => $groupBuyId,
  204. 'orderSn' => $order->orderSn,
  205. 'totalPrice' => $order->actPrice,
  206. 'id' => $order->id,
  207. ]);
  208. } catch (\Exception $e) {
  209. $transaction->rollBack();
  210. Yii::error('开团失败:' . $e->getMessage(), __METHOD__);
  211. $msg = $e->getMessage();
  212. if ($msg !== '' && mb_strlen($msg) < 80 && strpos($msg, 'SQLSTATE') === false) {
  213. util::fail($msg);
  214. }
  215. util::fail('开团失败');
  216. }
  217. }
  218. /**
  219. * 我要参团:加入已有团 + 创建待支付订单
  220. */
  221. public function actionJoin()
  222. {
  223. $form = new JoinGroupBuyForm();
  224. $form->loadAndValidate();
  225. $mainId = intval($this->mainId);
  226. $custom = $this->custom;
  227. $currentShopId = intval(Yii::$app->request->get('account', 0));
  228. if (empty($custom)) {
  229. $hd = HdClass::getByCondition(['shopId' => $currentShopId, 'userId' => $this->userId], false, null, 'id, customId');
  230. if (empty($hd)) {
  231. // 客户与当前门店无关系时,立即建立
  232. if (empty($this->user) || empty($this->shop)) {
  233. util::fail('请先登录');
  234. }
  235. $respond = CustomClass::buildRelation($this->shop, $this->user);
  236. if (empty($respond) || empty($respond['custom'])) {
  237. util::fail('关联门店失败');
  238. }
  239. $custom = $respond['custom'];
  240. } else {
  241. $customId = $hd['customId'];
  242. $custom = CustomClass::getById($customId, true);
  243. }
  244. }
  245. $customId = intval($custom->id);
  246. $groupBuyId = intval($form->groupBuyId);
  247. $goodsNum = max(1, intval($form->goodsNum));
  248. $connection = Yii::$app->db;
  249. $transaction = $connection->beginTransaction();
  250. try {
  251. $group = GroupBuyClass::assertCanJoin($mainId, $groupBuyId, $customId);
  252. $row = GroupBuyActivityClass::getActiveGoodsRowById($mainId, intval($this->shopId), intval($group->activityGoodsId));
  253. if (empty($row)) {
  254. // 活动结束后仍允许在截止前参团:用团上快照价
  255. $row = [
  256. 'activityId' => intval($group->activityId),
  257. 'activityGoodsId' => intval($group->activityGoodsId),
  258. 'goodsId' => intval($group->goodsId),
  259. 'price' => floatval($group->price),
  260. 'limit' => 1,
  261. 'endTime' => intval($group->deadline),
  262. 'groupSize' => intval($group->needNum),
  263. 'virtualGroup' => intval($group->virtualGroup),
  264. 'virtualMinutes' => 0,
  265. ];
  266. }
  267. GroupBuyClass::assertPurchaseLimit($mainId, $customId, $row, $goodsNum);
  268. $order = $this->createGroupBuyOrder($form, $row, $groupBuyId, $goodsNum, $custom);
  269. GroupBuyMemberClass::bindOrderMember(
  270. $groupBuyId,
  271. $mainId,
  272. intval($this->shopId),
  273. $customId,
  274. intval($order->id),
  275. strval($order->orderSn),
  276. GroupBuyMemberClass::ROLE_MEMBER
  277. );
  278. $transaction->commit();
  279. util::success([
  280. 'groupBuyId' => $groupBuyId,
  281. 'orderSn' => $order->orderSn,
  282. 'totalPrice' => $order->actPrice,
  283. 'id' => $order->id,
  284. ]);
  285. } catch (\Exception $e) {
  286. $transaction->rollBack();
  287. Yii::error('参团失败:' . $e->getMessage(), __METHOD__);
  288. $msg = $e->getMessage();
  289. if ($msg !== '' && mb_strlen($msg) < 80 && strpos($msg, 'SQLSTATE') === false) {
  290. util::fail($msg);
  291. }
  292. util::fail('参团失败');
  293. }
  294. }
  295. /**
  296. * 我的拼团列表
  297. */
  298. public function actionMyList()
  299. {
  300. $mainId = intval($this->mainId);
  301. $custom = $this->custom;
  302. if (empty($custom)) {
  303. util::fail('请先登录');
  304. }
  305. util::success([
  306. 'list' => GroupBuyClass::getMyList($mainId, intval($custom->id)),
  307. ]);
  308. }
  309. /**
  310. * 组装并创建拼团订单(核价以后端活动商品为准)
  311. * 团购价已是活动优惠价:跳过会员折、门店满减、红包;运费/包装费与混合结算同源计算
  312. * 跑腿(sendType=2)走与混合单相同的 calcMixRunnerFreight,不信任前端报价
  313. *
  314. * @param object $form
  315. * @param array $row
  316. * @param int $groupBuyId
  317. * @param int $goodsNum
  318. * @return object
  319. */
  320. private function createGroupBuyOrder($form, $row, $groupBuyId, $goodsNum, $currenCustom = [])
  321. {
  322. $shop = $this->shop;
  323. $openShop = ShopClass::getOpenShop($shop);
  324. if ($openShop == 0) {
  325. util::fail('已休店');
  326. }
  327. $mainId = intval($this->mainId);
  328. $custom = $this->custom;
  329. if (empty($custom) && !empty($currenCustom)) {
  330. $custom = $currenCustom;
  331. }
  332. if (empty($custom)) {
  333. util::fail('请先登录');
  334. }
  335. $hd = $this->hd;
  336. $user = $this->user;
  337. $saleGoodsId = intval($row['goodsId']);
  338. $goodsInfo = GoodsClass::getById($saleGoodsId, true);
  339. if (empty($goodsInfo) || intval($goodsInfo->mainId) !== $mainId) {
  340. util::fail('没有找到商品');
  341. }
  342. $stock = intval($goodsInfo->stock ?? 0);
  343. if ($stock < $goodsNum) {
  344. util::fail('库存不足');
  345. }
  346. $unitPrice = floatval($row['price'] ?? 0);
  347. if ($unitPrice <= 0) {
  348. util::fail('团购价格异常');
  349. }
  350. $goodsPrice = bcmul($unitPrice, $goodsNum, 2);
  351. $sendType = intval($form->sendType ?? dict::getDict('sendType', 'shopGet'));
  352. // 商家配送(0)/跑腿(2)必须有收花人与坐标,与混合结算一致
  353. if (in_array($sendType, [dict::getDict('sendType', 'carGet'), dict::getDict('sendType', 'thirdSend')], true)) {
  354. if (empty($form->receiveUserName)) {
  355. util::fail('请填写收花人名字');
  356. }
  357. if (empty($form->receiveMobile) || !stringUtil::isMobile($form->receiveMobile)) {
  358. util::fail('请填写正确的收花人手机号');
  359. }
  360. if (empty($form->long) || empty($form->lat)) {
  361. util::fail('请先完善地址');
  362. }
  363. }
  364. // 商家配送(0)/跑腿(2)必填配送时间;自取与物流/快递不强制(与混合结算一致)
  365. if (in_array($sendType, [0, 2], true) && empty($form->reachPeriod)) {
  366. util::fail('请选择配送时间');
  367. }
  368. $customInfo = PsMethodClass::buildCustomInfo($hd, $custom);
  369. $additionalCosts = PsMethodClass::calcFeeForMallContext(
  370. $this->shopId,
  371. $mainId,
  372. $sendType,
  373. $goodsPrice,
  374. $goodsNum,
  375. intval($custom->id),
  376. $customInfo
  377. );
  378. $unMeetSendCost = $additionalCosts['sendCost'] ?? 0;
  379. $packingFee = $additionalCosts['packCost'] ?? 0;
  380. $psMethodError = PsMethodClass::checkLimit(
  381. $this->shopId,
  382. $mainId,
  383. $sendType,
  384. $goodsPrice,
  385. $goodsNum,
  386. $packingFee,
  387. $unMeetSendCost,
  388. intval($custom->id),
  389. $customInfo
  390. );
  391. if ($psMethodError !== '') {
  392. util::fail($psMethodError);
  393. }
  394. $freightType = intval($goodsInfo->freightType ?? 0);
  395. $resolvedProduct = [[
  396. 'productId' => $saleGoodsId,
  397. 'unitType' => 0,
  398. 'property' => 0,
  399. 'freightType' => $freightType,
  400. 'unitPrice' => $unitPrice,
  401. 'num' => $goodsNum,
  402. ]];
  403. $runnerSendCost = 0;
  404. $sendDistance = 0;
  405. $freightSource = '';
  406. // 跑腿距离运费与混合单同源;未达门槛附加运费仍由 calcFee 单独给出
  407. if ($sendType == dict::getDict('sendType', 'thirdSend')) {
  408. $mapSet = \biz\shop\classes\ShopClass::hasIntraCity($shop);
  409. $openIntraCity = $mapSet['openIntraCity'] ?? 0;
  410. $runnerPost = [
  411. 'receiveUserName' => strval($form->receiveUserName ?? ''),
  412. 'receiveMobile' => strval($form->receiveMobile ?? ''),
  413. 'address' => strval($form->address ?? ''),
  414. 'floor' => strval($form->floor ?? ''),
  415. 'city' => strval($form->city ?? ''),
  416. 'dist' => strval($form->dist ?? ''),
  417. 'long' => $form->long ?? '',
  418. 'lat' => $form->lat ?? '',
  419. 'deliveryPlatform' => strval($form->deliveryPlatform ?? ''),
  420. 'deliveryBracketContent' => strval($form->deliveryBracketContent ?? ''),
  421. 'remark' => strval($form->remark ?? ''),
  422. ];
  423. $runnerResult = PsMethodClass::calcMixRunnerFreight(
  424. $shop,
  425. $this->shopId,
  426. $mainId,
  427. $runnerPost,
  428. $resolvedProduct,
  429. 0,
  430. $goodsPrice,
  431. $openIntraCity,
  432. 0,
  433. $goodsNum,
  434. 'PT-GB-',
  435. '团购单'
  436. );
  437. $runnerSendCost = $runnerResult['sendCost'];
  438. $sendDistance = $runnerResult['sendDistance'];
  439. $freightSource = $runnerResult['freightSource'];
  440. }
  441. $sendCost = bcadd($unMeetSendCost, $runnerSendCost, 2);
  442. $modifyPrice = bcadd($goodsPrice, $sendCost, 2);
  443. $modifyPrice = bcadd($modifyPrice, $packingFee, 2);
  444. $post = [
  445. 'sendType' => $sendType,
  446. 'receiveUserName' => strval($form->receiveUserName ?? ''),
  447. 'receiveMobile' => strval($form->receiveMobile ?? ''),
  448. 'address' => strval($form->address ?? ''),
  449. 'floor' => strval($form->floor ?? ''),
  450. 'city' => strval($form->city ?? ''),
  451. 'dist' => strval($form->dist ?? ''),
  452. 'province' => strval($form->province ?? ''),
  453. 'long' => strval($form->long ?? ''),
  454. 'lat' => strval($form->lat ?? ''),
  455. 'showAddress' => strval($form->showAddress ?? ''),
  456. 'remark' => strval($form->remark ?? ''),
  457. 'reachDate' => !empty($form->reachDate) ? $form->reachDate : date('Y-m-d'),
  458. 'reachPeriod' => strval($form->reachPeriod ?? ''),
  459. 'sendCost' => $sendCost,
  460. 'packingFee' => $packingFee,
  461. 'sendDistance' => $sendDistance,
  462. 'freightSource' => $freightSource,
  463. 'runnerSendCost' => $runnerSendCost,
  464. 'needCard' => intval($form->needCard ?? 0),
  465. 'cardInfo' => intval($form->needCard ?? 0) === 1 ? strval($form->cardInfo ?? '') : '',
  466. 'anonymity' => intval($form->anonymity ?? 0),
  467. 'sjId' => intval($this->sjId ?: ($shop->sjId ?? 0)),
  468. 'shopId' => $this->shopId,
  469. 'mainId' => $mainId,
  470. 'userId' => $this->userId,
  471. 'customId' => intval($custom->id),
  472. 'customName' => strval($custom->name ?? ''),
  473. 'customNamePy' => stringUtil::py(strval($custom->name ?? '')),
  474. 'hdId' => intval($hd->id ?? 0),
  475. 'hdName' => strval($hd->name ?? ''),
  476. 'bookName' => strval($user->name ?? ''),
  477. 'bookMobile' => !empty($form->bookMobile) && stringUtil::isMobile($form->bookMobile)
  478. ? $form->bookMobile
  479. : strval($user->mobile ?? ''),
  480. 'payWay' => 0,
  481. 'store' => 0,
  482. 'modifyPrice' => $modifyPrice,
  483. 'deadline' => time() + 1800,
  484. 'orderSn' => orderSn::getOrderSn(),
  485. 'fromType' => dict::getDict('fromType', 'mall'),
  486. 'cash' => 0,
  487. 'needPrint' => dict::getDict('needPrint', 'need'),
  488. 'groupBuyId' => intval($groupBuyId),
  489. // 拼团价已是活动价:跳过会员折、门店满减、红包,避免再叠优惠
  490. 'skipMemberDiscount' => 1,
  491. 'skipShopMeetCut' => 1,
  492. 'hbId' => 0,
  493. 'hbAmount' => 0,
  494. 'product' => $resolvedProduct,
  495. ];
  496. return OrderService::createHdOrder($post, $custom, 0);
  497. }
  498. }