Lottery.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\Service\Lottery\LotteryService;
  5. use app\common\Service\Lottery\LotteryChanceService;
  6. use app\common\Service\Lottery\LotteryRecordService;
  7. use app\common\Service\Lottery\LotteryActivityService;
  8. use app\common\model\lottery\LotteryActivity;
  9. use app\common\model\lottery\LotteryPrize;
  10. use app\common\model\lottery\LotteryWinRecord;
  11. use app\common\library\Auth;
  12. use app\api\validate\Lottery as LotteryValidate;
  13. use app\common\Enum\ActivityEnum;
  14. use app\common\Enum\LotteryEnum;
  15. use app\common\exception\BusinessException;
  16. use app\common\Enum\ErrorCodeEnum;
  17. use think\Exception;
  18. use app\common\Service\OrderService;
  19. /**
  20. * 抽奖API控制器
  21. */
  22. class Lottery extends Api
  23. {
  24. protected $noNeedLogin = ['activityList', 'activityDetail', 'getPrizes'];
  25. protected $noNeedRight = ['*'];
  26. /**
  27. * 获取抽奖活动列表
  28. */
  29. public function getActivityList()
  30. {
  31. // 验证参数
  32. $validate = new LotteryValidate();
  33. $params = $this->request->param();
  34. if (!$validate->scene('activityList')->check($params)) {
  35. $this->error($validate->getError());
  36. }
  37. $page = $params['page'] ?? 1;
  38. $limit = $params['pageSize'] ?? 10;
  39. $status = $params['status'] ?? ActivityEnum::ACTIVITY_STATUS_ONGOING; // 默认只返回进行中的活动
  40. $where = [];
  41. if ($status !== '') {
  42. $where['status'] = $status;
  43. }
  44. // 只返回进行中且在时间范围内的活动
  45. $now = time();
  46. $where['start_time'] = ['<=', $now];
  47. $where['end_time'] = ['>=', $now];
  48. $activities = LotteryActivity::where($where)
  49. ->field('id,name,description,cover_image,type,status,start_time,end_time,lottery_type,guide_image,guide_text,intro_content')
  50. ->order('createtime desc')
  51. ->page($page, $limit)
  52. ->select();
  53. $list = [];
  54. foreach ($activities as $activity) {
  55. $item = $activity->toArray();
  56. // 获取奖品信息
  57. $prizes = LotteryPrize::where('activity_id', $activity->id)
  58. ->where('status', 1)
  59. ->where('type', '>', 1) // 排除未中奖类型
  60. ->field('id,name,type,image,probability')
  61. ->order('sort_order asc')
  62. ->select();
  63. $item['prizes'] = $prizes;
  64. // 统计信息
  65. $item['total_participants'] = LotteryChanceService::getActivityParticipants($activity->id);
  66. $list[] = $item;
  67. }
  68. $this->success('获取成功', [
  69. 'list' => $list,
  70. 'total' => LotteryActivity::where($where)->count()
  71. ]);
  72. }
  73. /**
  74. * 获取活动详情
  75. */
  76. public function getActivityDetail()
  77. {
  78. // 验证参数
  79. $validate = new LotteryValidate();
  80. if (!$validate->scene('activityDetail')->check($this->request->param())) {
  81. $this->error($validate->getError());
  82. }
  83. $activityId = $this->request->param('lottery_id/d');
  84. $activity = LotteryActivity::find($activityId);
  85. if (!$activity) {
  86. throw new BusinessException('活动不存在', ErrorCodeEnum::USER_ACTIVITY_NOT_FOUND);
  87. }
  88. $detail = $activity->toArray();
  89. // 获取奖品列表
  90. $prizes = LotteryPrize::where('activity_id', $activityId)
  91. ->where('status', 1)
  92. ->field('id,name,type,image,description,probability,total_stock,remain_stock,win_prompt,sort_order,unlock_people_num')
  93. ->order('sort_order asc')
  94. ->select();
  95. // 检查奖品是否已解锁(如果开启按人数解锁)
  96. if ($activity->unlock_by_people) {
  97. $currentPeopleCount = LotteryChanceService::getActivityParticipants($activityId);
  98. foreach ($prizes as &$prize) {
  99. $prize['is_unlocked'] = $prize->isUnlocked($currentPeopleCount);
  100. }
  101. } else {
  102. foreach ($prizes as &$prize) {
  103. $prize['is_unlocked'] = true;
  104. }
  105. }
  106. $detail['prizes'] = $prizes;
  107. // 统计信息
  108. $detail['total_participants'] = LotteryChanceService::getActivityParticipants($activityId);
  109. // 如果用户已登录,返回用户相关信息
  110. if (Auth::instance()->isLogin()) {
  111. $userId = Auth::instance()->id;
  112. $detail['user_chances'] = LotteryService::getUserChances($activityId, $userId);
  113. $detail['user_draw_count'] = LotteryRecordService::getUserDrawCount($activityId, $userId);
  114. $detail['user_win_count'] = LotteryRecordService::getUserWinCount($activityId, $userId);
  115. }
  116. $this->success('获取成功', $detail);
  117. }
  118. /**
  119. * 执行抽奖
  120. */
  121. public function draw()
  122. {
  123. // 验证参数
  124. $validate = new LotteryValidate();
  125. if (!$validate->scene('draw')->check($this->request->param())) {
  126. $this->error($validate->getError());
  127. }
  128. $activityId = $this->request->post('lottery_id/d');
  129. $userId = $this->auth->id;
  130. $result = LotteryService::drawLottery($activityId, $userId);
  131. $this->success('抽奖成功', $result);
  132. }
  133. /**
  134. * 获取用户抽奖机会
  135. */
  136. public function getUserChances()
  137. {
  138. // 验证参数
  139. $validate = new LotteryValidate();
  140. if (!$validate->scene('getUserChances')->check($this->request->param())) {
  141. $this->error($validate->getError());
  142. }
  143. $activityId = $this->request->post('lottery_id/d');
  144. $userId = $this->auth->id;
  145. $chances = LotteryChanceService::getUserChanceDetail($activityId, $userId);
  146. $this->success('获取成功', $chances);
  147. }
  148. /**
  149. * 获取用户抽奖记录
  150. */
  151. public function getDrawRecords()
  152. {
  153. // 验证参数(activity_id可选)
  154. $params = $this->request->param();
  155. $validate = new LotteryValidate();
  156. // 如果有activity_id参数,则把它映射为activity_id_optional进行验证
  157. $validateParams = $params;
  158. if (isset($params['lottery_id'])) {
  159. $validateParams['activity_id_optional'] = $params['lottery_id'];
  160. unset($validateParams['lottery_id']);
  161. }
  162. if (isset($params['status'])) {
  163. $validateParams['record_status'] = $params['status'];
  164. unset($validateParams['status']);
  165. }
  166. if (!$validate->scene('getDrawRecords')->check($validateParams)) {
  167. $this->error($validate->getError());
  168. }
  169. $activityId = $this->request->post('lottery_id/d');
  170. $page = $this->request->param('page/d', 1);
  171. $pageSize = $this->request->param('pageSize/d', 10);
  172. $status = $params['status'] ?? 1;
  173. $userId = $this->auth->id;
  174. $records = LotteryRecordService::getUserDrawRecords($userId, $activityId, $status, $page, $pageSize);
  175. $this->success('获取成功', $records);
  176. }
  177. /**
  178. * 获取抽奖记录详情
  179. */
  180. public function getDrawRecordDetail()
  181. {
  182. $drawRecordId = $this->request->get('draw_record_id/d');
  183. $validate = new LotteryValidate();
  184. if (!$validate->scene('getDrawRecordDetail')->check(['draw_record_id' => $drawRecordId])) {
  185. $this->error($validate->getError());
  186. }
  187. $userId = $this->auth->id;
  188. $drawRecord = LotteryRecordService::getDrawRecordDetail($drawRecordId, $userId);
  189. $this->success('获取成功', $drawRecord);
  190. }
  191. /**
  192. * 获取用户中奖记录
  193. */
  194. public function getWinRecords()
  195. {
  196. // 验证参数
  197. $validate = new LotteryValidate();
  198. if (!$validate->scene('getWinRecords')->check($this->request->param())) {
  199. $this->error($validate->getError());
  200. }
  201. $page = $this->request->param('page/d', 1);
  202. $pageSize = $this->request->param('pageSize/d', 20);
  203. $userId = $this->auth->id;
  204. $records = LotteryRecordService::getUserWinRecords($userId, $page, $pageSize);
  205. $list = [];
  206. foreach ($records as $record) {
  207. $item = [
  208. 'id' => $record->id,
  209. 'activity_id' => $record->activity_id,
  210. 'activity_name' => $record->activity->name ?? '',
  211. 'prize_id' => $record->prize_id,
  212. 'prize_name' => $record->prize_name,
  213. 'prize_type' => $record->prize_type,
  214. 'deliver_status' => $record->deliver_status,
  215. 'deliver_status_text' => $record->deliver_status_text,
  216. 'deliver_time' => $record->deliver_time,
  217. 'exchange_code' => $record->exchange_code,
  218. 'createtime' => $record->createtime
  219. ];
  220. // 根据奖品类型返回特定信息
  221. $prizeValue = $record->prize_value_data;
  222. switch ($record->prize_type) {
  223. case LotteryEnum::PRIZE_TYPE_REDPACK:
  224. $item['amount'] = $prizeValue['amount'] ?? 0;
  225. break;
  226. case LotteryEnum::PRIZE_TYPE_COUPON:
  227. $item['coupon_id'] = $prizeValue['coupon_id'] ?? 0;
  228. break;
  229. case LotteryEnum::PRIZE_TYPE_GOODS:
  230. $item['goods_id'] = $prizeValue['goods_id'] ?? 0;
  231. $item['goods_sku_id'] = $prizeValue['goods_sku_id'] ?? 0;
  232. break;
  233. }
  234. // 奖品图片
  235. $item['prize_image'] = cdnurl($item['prize_image']);
  236. $list[] = $item;
  237. }
  238. $this->success('获取成功', [
  239. 'list' => $list,
  240. 'total' => LotteryRecordService::getUserWinRecords($userId, 1, 1)->count()
  241. ]);
  242. }
  243. /**
  244. * 设置中奖记录收货地址
  245. */
  246. public function setWinRecordAddress()
  247. {
  248. // 验证参数
  249. $validate = new LotteryValidate();
  250. if (!$validate->scene('setWinRecordAddress')->check($this->request->param())) {
  251. $this->error($validate->getError());
  252. }
  253. $winRecordId = $this->request->param('win_record_id/d');
  254. $receiverName = $this->request->param('receiver_name');
  255. $receiverMobile = $this->request->param('receiver_mobile');
  256. $receiverAddress = $this->request->param('receiver_address');
  257. $userId = $this->auth->id;
  258. // 验证 中奖记录 是否存在
  259. $winRecord = LotteryRecordService::getWinRecordDetail($winRecordId, $userId);
  260. if (!$winRecord) {
  261. $this->error('中奖记录不存在');
  262. }
  263. if ($winRecord->deliver_status != LotteryEnum::DELIVER_STATUS_PENDING) {
  264. $this->error('该奖品已处理,无法修改地址');
  265. }
  266. try {
  267. LotteryRecordService::setWinRecordDeliveryAddress($winRecord, $receiverName, $receiverMobile, $receiverAddress);
  268. $this->success('设置成功');
  269. } catch (Exception $e) {
  270. $this->error('设置失败:' . $e->getMessage());
  271. }
  272. }
  273. /**
  274. * 获取活动排行榜(中奖次数)
  275. */
  276. public function getRanking()
  277. {
  278. // 验证参数
  279. $validate = new LotteryValidate();
  280. if (!$validate->scene('getRanking')->check($this->request->param())) {
  281. $this->error($validate->getError());
  282. }
  283. $activityId = $this->request->param('activity_id/d');
  284. $page = $this->request->param('page/d', 1);
  285. $limit = $this->request->param('limit/d', 50);
  286. // 统计用户中奖次数
  287. $ranking = LotteryRecordService::getActivityDrawRanking($activityId, $limit);
  288. $list = [];
  289. $rank = ($page - 1) * $limit + 1;
  290. foreach ($ranking as $item) {
  291. $list[] = [
  292. 'rank' => $rank++,
  293. 'user_id' => $item->user_id,
  294. 'nickname' => $item->user->nickname ?? '匿名用户',
  295. 'avatar' => $item->user->avatar ?? '',
  296. 'win_count' => $item->win_count ?? 0
  297. ];
  298. }
  299. $this->success('获取成功', $list);
  300. }
  301. /**
  302. * 获取奖品列表
  303. */
  304. public function getPrizes()
  305. {
  306. // 验证参数
  307. $validate = new LotteryValidate();
  308. $params = $this->request->param();
  309. if (!$validate->scene('getPrizes')->check($params)) {
  310. $this->error($validate->getError());
  311. }
  312. $activityId = $params['lottery_id'] ?? 0;
  313. $page = $params['page'] ?? 1;
  314. $pageSize = $params['pageSize'] ?? 10;
  315. $type = $params['type'] ?? null; // 奖品类型筛选,支持逗号分隔字符串
  316. // 调用服务层方法
  317. $paginate = LotteryActivityService::getPrizes($activityId, $page, $pageSize, $type);
  318. // 处理图片 地址
  319. foreach ($paginate as $item) {
  320. $item['image'] = $item['image'] ? cdnurl($item['image']) : '';
  321. }
  322. $this->success('获取成功', $paginate);
  323. }
  324. // 订单完成后 分发抽奖机会
  325. public function getLotteryChanceByOrder()
  326. {
  327. $orderId = $this->request->post('order_id/d');
  328. // 验证器
  329. $validate = new LotteryValidate();
  330. if (!$validate->scene('getLotteryChanceByOrder')->check(['order_id' => $orderId])) {
  331. $this->error($validate->getError());
  332. }
  333. $userId = $this->auth->id;
  334. $orderInfo = OrderService::getDetail($orderId, $userId);
  335. if(!$orderInfo){
  336. $this->error('订单不存在');
  337. }
  338. // 是否是已支付
  339. if(!$orderInfo->isPayStatus()){
  340. $this->error('订单未支付');
  341. }
  342. // 构造数据
  343. $goodsList = $orderInfo->orderGoods;
  344. $goodsList = collection($goodsList)->toArray();
  345. $goodsList = array_map(function($item){
  346. return [
  347. 'goods_id' => $item['goods_id'],
  348. ];
  349. }, $goodsList);
  350. $orderInfo = [
  351. 'id' => $orderInfo->id,
  352. 'total_amount' => $orderInfo->amount,
  353. 'goods' => $goodsList
  354. ];
  355. // 获取当前正在进行的单个抽奖活动
  356. $activity = LotteryActivityService::getCurrentRunningActivity();
  357. // 如果没有正在进行的活动,返回null
  358. if (!$activity) {
  359. $this->success('获取成功', null);
  360. }
  361. // 用户 订单 是否已经分发过 抽奖机会
  362. $isGranted = LotteryChanceService::isGrantedChanceForOrder($orderInfo, $userId);
  363. if($isGranted){
  364. // 直接返回 所剩 机会
  365. $userChance = LotteryChanceService::getUserChance($activity->id, $userId);
  366. $arrReturn = [
  367. 'lottery_id' => $activity->id,
  368. 'lottery_type' => $activity->lottery_type,
  369. 'lottery_name' => $activity->name,
  370. 'chances' => $userChance->total_chances,
  371. ];
  372. $this->success('获取成功', $arrReturn);
  373. }
  374. $grantedChances = LotteryChanceService::checkAndGrantChanceForOrderOne($activity, $orderInfo, $userId);
  375. $this->success('获取成功', $grantedChances);
  376. }
  377. }