LotteryRecordService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php
  2. namespace app\common\Service\Lottery;
  3. use app\common\model\lottery\LotteryDrawRecord;
  4. use app\common\model\lottery\LotteryWinRecord;
  5. use app\common\model\lottery\LotteryPrize;
  6. use app\common\Enum\LotteryEnum;
  7. use think\Exception;
  8. /**
  9. * 抽奖记录服务类
  10. * 专门处理抽奖记录和中奖记录的业务逻辑
  11. */
  12. class LotteryRecordService
  13. {
  14. // ============ 抽奖记录相关方法 ============
  15. /**
  16. * 创建抽奖记录
  17. */
  18. public static function createDrawRecord($activityId, $userId, $prizeId, $isWin, $triggerType, $triggerOrderId = null, $triggerAmount = null, $winInfo = [])
  19. {
  20. $data = [
  21. 'activity_id' => $activityId,
  22. 'user_id' => $userId,
  23. 'prize_id' => $prizeId,
  24. 'is_win' => $isWin ? 1 : 0,
  25. 'trigger_type' => $triggerType,
  26. 'trigger_order_id' => $triggerOrderId,
  27. 'trigger_amount' => $triggerAmount,
  28. 'win_info' => $winInfo ? json_encode($winInfo) : '',
  29. 'draw_ip' => request()->ip(),
  30. 'draw_time' => time(),
  31. 'device_info' => request()->header('user-agent', '')
  32. ];
  33. return LotteryDrawRecord::create($data);
  34. }
  35. /**
  36. * 获取用户抽奖次数
  37. */
  38. public static function getUserDrawCount($activityId, $userId, $timeRange = null)
  39. {
  40. $query = LotteryDrawRecord::where('activity_id', $activityId)
  41. ->where('user_id', $userId);
  42. if ($timeRange) {
  43. if (isset($timeRange['start'])) {
  44. $query->where('draw_time', '>=', $timeRange['start']);
  45. }
  46. if (isset($timeRange['end'])) {
  47. $query->where('draw_time', '<=', $timeRange['end']);
  48. }
  49. }
  50. return $query->count();
  51. }
  52. /**
  53. * 获取用户中奖次数
  54. */
  55. public static function getUserWinCount($activityId, $userId, $timeRange = null)
  56. {
  57. $query = LotteryDrawRecord::where('activity_id', $activityId)
  58. ->where('user_id', $userId)
  59. ->where('is_win', 1);
  60. if ($timeRange) {
  61. if (isset($timeRange['start'])) {
  62. $query->where('draw_time', '>=', $timeRange['start']);
  63. }
  64. if (isset($timeRange['end'])) {
  65. $query->where('draw_time', '<=', $timeRange['end']);
  66. }
  67. }
  68. return $query->count();
  69. }
  70. /**
  71. * 获取活动抽奖统计
  72. */
  73. public static function getActivityDrawStats($activityId, $timeRange = null)
  74. {
  75. $query = LotteryDrawRecord::where('activity_id', $activityId);
  76. if ($timeRange) {
  77. if (isset($timeRange['start'])) {
  78. $query->where('draw_time', '>=', $timeRange['start']);
  79. }
  80. if (isset($timeRange['end'])) {
  81. $query->where('draw_time', '<=', $timeRange['end']);
  82. }
  83. }
  84. return [
  85. 'total_draw' => $query->count(),
  86. 'total_win' => $query->where('is_win', 1)->count(),
  87. 'total_people' => $query->distinct('user_id')->count()
  88. ];
  89. }
  90. /**
  91. * 获取用户抽奖记录列表
  92. */
  93. public static function getUserDrawRecords($userId, $activityId = null, $page = 1, $limit = 20)
  94. {
  95. $query = LotteryDrawRecord::where('user_id', $userId);
  96. if ($activityId) {
  97. $query->where('activity_id', $activityId);
  98. }
  99. return $query->with(['activity', 'prize', 'winRecord'])
  100. ->order('draw_time', 'desc')
  101. ->page($page, $limit)
  102. ->select();
  103. }
  104. /**
  105. * 获取活动抽奖记录列表
  106. */
  107. public static function getActivityDrawRecords($activityId, $page = 1, $limit = 20, $filters = [])
  108. {
  109. $query = LotteryDrawRecord::where('activity_id', $activityId);
  110. // 应用过滤器
  111. if (isset($filters['is_win'])) {
  112. $query->where('is_win', $filters['is_win']);
  113. }
  114. if (isset($filters['trigger_type'])) {
  115. $query->where('trigger_type', $filters['trigger_type']);
  116. }
  117. if (isset($filters['start_time'])) {
  118. $query->where('draw_time', '>=', $filters['start_time']);
  119. }
  120. if (isset($filters['end_time'])) {
  121. $query->where('draw_time', '<=', $filters['end_time']);
  122. }
  123. return $query->with(['user', 'prize', 'winRecord'])
  124. ->order('draw_time', 'desc')
  125. ->page($page, $limit)
  126. ->select();
  127. }
  128. /**
  129. * 获取抽奖记录详情
  130. */
  131. public static function getDrawRecordDetail($drawRecordId)
  132. {
  133. return LotteryDrawRecord::where('id', $drawRecordId)
  134. ->with(['activity', 'user', 'prize', 'winRecord', 'order'])
  135. ->find();
  136. }
  137. /**
  138. * 检查用户是否已为指定订单抽奖
  139. */
  140. public static function hasUserDrawnForOrder($activityId, $userId, $orderId)
  141. {
  142. return LotteryDrawRecord::where('activity_id', $activityId)
  143. ->where('user_id', $userId)
  144. ->where('trigger_order_id', $orderId)
  145. ->count() > 0;
  146. }
  147. /**
  148. * 获取用户抽奖历史统计
  149. */
  150. public static function getUserDrawHistoryStats($userId)
  151. {
  152. $stats = LotteryDrawRecord::where('user_id', $userId)
  153. ->field([
  154. 'COUNT(*) as total_draws',
  155. 'SUM(is_win) as total_wins',
  156. 'COUNT(DISTINCT activity_id) as total_activities'
  157. ])
  158. ->find();
  159. return [
  160. 'total_draws' => $stats['total_draws'] ?? 0,
  161. 'total_wins' => $stats['total_wins'] ?? 0,
  162. 'total_activities' => $stats['total_activities'] ?? 0,
  163. 'win_rate' => $stats['total_draws'] > 0 ?
  164. round(($stats['total_wins'] / $stats['total_draws']) * 100, 2) : 0
  165. ];
  166. }
  167. /**
  168. * 获取活动抽奖排行榜
  169. */
  170. public static function getActivityDrawRanking($activityId, $limit = 50)
  171. {
  172. return LotteryDrawRecord::where('activity_id', $activityId)
  173. ->field('user_id, COUNT(*) as draw_count, SUM(is_win) as win_count')
  174. ->with('user')
  175. ->group('user_id')
  176. ->order('draw_count desc, win_count desc')
  177. ->limit($limit)
  178. ->select();
  179. }
  180. /**
  181. * 获取活动抽奖时间分布统计
  182. */
  183. public static function getActivityDrawTimeDistribution($activityId, $dateRange = null)
  184. {
  185. $query = LotteryDrawRecord::where('activity_id', $activityId);
  186. if ($dateRange) {
  187. if (isset($dateRange['start'])) {
  188. $query->where('draw_time', '>=', $dateRange['start']);
  189. }
  190. if (isset($dateRange['end'])) {
  191. $query->where('draw_time', '<=', $dateRange['end']);
  192. }
  193. }
  194. return $query->field('DATE(FROM_UNIXTIME(draw_time)) as date, COUNT(*) as draw_count, SUM(is_win) as win_count')
  195. ->group('date')
  196. ->order('date asc')
  197. ->select();
  198. }
  199. // ============ 中奖记录相关方法 ============
  200. /**
  201. * 创建中奖记录
  202. */
  203. public static function createWinRecord($drawRecordId, $activityId, $userId, $prizeId, $prizeName, $prizeType, $prizeValue = [])
  204. {
  205. $data = [
  206. 'draw_record_id' => $drawRecordId,
  207. 'activity_id' => $activityId,
  208. 'user_id' => $userId,
  209. 'prize_id' => $prizeId,
  210. 'prize_name' => $prizeName,
  211. 'prize_type' => $prizeType,
  212. 'prize_value' => is_array($prizeValue) ? json_encode($prizeValue) : $prizeValue,
  213. 'deliver_status' => LotteryEnum::DELIVER_STATUS_PENDING
  214. ];
  215. return LotteryWinRecord::create($data);
  216. }
  217. /**
  218. * 标记中奖记录为发放成功
  219. */
  220. public static function markWinRecordAsDelivered(LotteryWinRecord $winRecord, $deliverInfo = [])
  221. {
  222. $winRecord->deliver_status = LotteryEnum::DELIVER_STATUS_SUCCESS;
  223. $winRecord->deliver_time = time();
  224. if ($deliverInfo) {
  225. $winRecord->deliver_info = json_encode($deliverInfo);
  226. }
  227. return $winRecord->save();
  228. }
  229. /**
  230. * 标记中奖记录为发放失败
  231. */
  232. public static function markWinRecordAsFailed(LotteryWinRecord $winRecord, $reason = '')
  233. {
  234. $winRecord->deliver_status = LotteryEnum::DELIVER_STATUS_FAILED;
  235. $winRecord->fail_reason = $reason;
  236. return $winRecord->save();
  237. }
  238. /**
  239. * 设置中奖记录收货地址
  240. */
  241. public static function setWinRecordDeliveryAddress(LotteryWinRecord $winRecord, $name, $mobile, $address)
  242. {
  243. $winRecord->receiver_name = $name;
  244. $winRecord->receiver_mobile = $mobile;
  245. $winRecord->receiver_address = $address;
  246. return $winRecord->save();
  247. }
  248. /**
  249. * 设置中奖记录快递信息
  250. */
  251. public static function setWinRecordExpressInfo(LotteryWinRecord $winRecord, $company, $number)
  252. {
  253. $winRecord->express_company = $company;
  254. $winRecord->express_number = $number;
  255. return $winRecord->save();
  256. }
  257. /**
  258. * 设置中奖记录兑换码
  259. */
  260. public static function setWinRecordExchangeCode(LotteryWinRecord $winRecord, $code)
  261. {
  262. $winRecord->exchange_code = $code;
  263. return $winRecord->save();
  264. }
  265. /**
  266. * 标记中奖记录兑换码已使用
  267. */
  268. public static function markWinRecordCodeUsed(LotteryWinRecord $winRecord)
  269. {
  270. $winRecord->code_used_time = time();
  271. return $winRecord->save();
  272. }
  273. /**
  274. * 获取待发放的中奖记录
  275. */
  276. public static function getPendingWinRecords($limit = 100)
  277. {
  278. return LotteryWinRecord::where('deliver_status', LotteryEnum::DELIVER_STATUS_PENDING)
  279. ->order('createtime', 'asc')
  280. ->limit($limit)
  281. ->select();
  282. }
  283. /**
  284. * 获取用户中奖记录
  285. */
  286. public static function getUserWinRecords($userId, $page = 1, $limit = 20)
  287. {
  288. return LotteryWinRecord::where('user_id', $userId)
  289. ->with(['activity', 'prize'])
  290. ->order('createtime', 'desc')
  291. ->page($page, $limit)
  292. ->select();
  293. }
  294. /**
  295. * 获取活动中奖统计
  296. */
  297. public static function getActivityWinStats($activityId)
  298. {
  299. return [
  300. 'total_win' => LotteryWinRecord::where('activity_id', $activityId)->count(),
  301. 'delivered' => LotteryWinRecord::where('activity_id', $activityId)
  302. ->where('deliver_status', LotteryEnum::DELIVER_STATUS_SUCCESS)
  303. ->count(),
  304. 'pending' => LotteryWinRecord::where('activity_id', $activityId)
  305. ->where('deliver_status', LotteryEnum::DELIVER_STATUS_PENDING)
  306. ->count(),
  307. 'failed' => LotteryWinRecord::where('activity_id', $activityId)
  308. ->where('deliver_status', LotteryEnum::DELIVER_STATUS_FAILED)
  309. ->count()
  310. ];
  311. }
  312. /**
  313. * 批量处理待发放的中奖记录
  314. */
  315. public static function batchProcessPendingWinRecords($limit = 50)
  316. {
  317. $pendingRecords = static::getPendingWinRecords($limit);
  318. $processedCount = 0;
  319. foreach ($pendingRecords as $winRecord) {
  320. try {
  321. $prize = LotteryPrize::find($winRecord->prize_id);
  322. if ($prize && $prize->deliver_type == LotteryEnum::DELIVER_TYPE_AUTO) {
  323. static::autoDeliverPrize($winRecord, $prize);
  324. $processedCount++;
  325. }
  326. } catch (Exception $e) {
  327. static::markWinRecordAsFailed($winRecord, $e->getMessage());
  328. trace('自动发放奖品失败: ' . $e->getMessage(), 'error');
  329. }
  330. }
  331. return $processedCount;
  332. }
  333. /**
  334. * 手动发放奖品(管理员操作)
  335. */
  336. public static function manualDeliverPrize($winRecordId, $deliverInfo = [], $adminId = 0)
  337. {
  338. $winRecord = LotteryWinRecord::find($winRecordId);
  339. if (!$winRecord) {
  340. throw new Exception('中奖记录不存在');
  341. }
  342. if ($winRecord->deliver_status != LotteryEnum::DELIVER_STATUS_PENDING) {
  343. throw new Exception('该记录已处理,无法重复发放');
  344. }
  345. $deliverInfo['admin_id'] = $adminId;
  346. $deliverInfo['manual_deliver_time'] = time();
  347. return static::markWinRecordAsDelivered($winRecord, $deliverInfo);
  348. }
  349. /**
  350. * 取消中奖记录
  351. */
  352. public static function cancelWinRecord($winRecordId, $reason = '', $adminId = 0)
  353. {
  354. $winRecord = LotteryWinRecord::find($winRecordId);
  355. if (!$winRecord) {
  356. throw new Exception('中奖记录不存在');
  357. }
  358. $winRecord->deliver_status = LotteryEnum::DELIVER_STATUS_CANCELLED;
  359. $winRecord->fail_reason = $reason;
  360. $winRecord->cancel_time = time();
  361. $winRecord->cancel_admin_id = $adminId;
  362. return $winRecord->save();
  363. }
  364. /**
  365. * 自动发放奖品
  366. */
  367. public static function autoDeliverPrize($winRecord, $prize)
  368. {
  369. try {
  370. switch ($prize->type) {
  371. case LotteryEnum::PRIZE_TYPE_COUPON:
  372. static::deliverCoupon($winRecord, $prize);
  373. break;
  374. case LotteryEnum::PRIZE_TYPE_REDPACK:
  375. static::deliverRedPacket($winRecord, $prize);
  376. break;
  377. case LotteryEnum::PRIZE_TYPE_CODE:
  378. static::deliverExchangeCode($winRecord, $prize);
  379. break;
  380. case LotteryEnum::PRIZE_TYPE_SHOP_GOODS:
  381. static::deliverGoods($winRecord, $prize);
  382. break;
  383. }
  384. } catch (Exception $e) {
  385. static::markWinRecordAsFailed($winRecord, $e->getMessage());
  386. }
  387. }
  388. /**
  389. * 发放优惠券
  390. */
  391. private static function deliverCoupon($winRecord, $prize)
  392. {
  393. // 这里调用优惠券发放接口
  394. // 示例代码,需要根据实际优惠券系统实现
  395. static::markWinRecordAsDelivered($winRecord, ['coupon_id' => $prize->coupon_id]);
  396. }
  397. /**
  398. * 发放红包
  399. */
  400. private static function deliverRedPacket($winRecord, $prize)
  401. {
  402. // 这里调用红包发放接口
  403. // 示例代码,需要根据实际红包系统实现
  404. static::markWinRecordAsDelivered($winRecord, ['amount' => $prize->amount]);
  405. }
  406. /**
  407. * 发放兑换码
  408. */
  409. private static function deliverExchangeCode($winRecord, $prize)
  410. {
  411. $code = LotteryService::getAvailableExchangeCode($prize);
  412. if ($code) {
  413. static::setWinRecordExchangeCode($winRecord, $code);
  414. LotteryService::markExchangeCodeUsed($prize, $code);
  415. static::markWinRecordAsDelivered($winRecord, ['exchange_code' => $code]);
  416. } else {
  417. throw new Exception('兑换码已用完');
  418. }
  419. }
  420. /**
  421. * 发放商城商品
  422. */
  423. private static function deliverGoods($winRecord, $prize)
  424. {
  425. // 这里可以自动加入购物车或创建订单
  426. // 示例代码,需要根据实际商城系统实现
  427. static::markWinRecordAsDelivered($winRecord, [
  428. 'goods_id' => $prize->goods_id,
  429. 'goods_sku_id' => $prize->goods_sku_id
  430. ]);
  431. }
  432. }