Lottery.php 14 KB

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