LotteryChanceService.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. <?php
  2. namespace app\common\Service\Lottery;
  3. use app\common\model\lottery\LotteryActivity;
  4. use app\common\model\lottery\LotteryCondition;
  5. use app\common\model\lottery\LotteryUserChance;
  6. use app\common\model\lottery\LotteryUserChanceRecord;
  7. use app\common\model\User;
  8. use app\common\model\Order;
  9. use app\common\Enum\LotteryEnum;
  10. use think\Exception;
  11. use think\Db;
  12. use app\common\exception\BusinessException;
  13. use app\common\Enum\OrderEnum;
  14. use app\common\Service\Lottery\LotteryActivityService;
  15. /**
  16. * 抽奖机会服务类
  17. * 处理用户获得抽奖机会的逻辑
  18. *
  19. * 主要功能:
  20. * - 订单/充值后自动分发抽奖机会
  21. * - 条件验证和机会计算
  22. * - 用户机会管理
  23. * - 批量操作和统计
  24. */
  25. class LotteryChanceService
  26. {
  27. // ============ 常量定义 ============
  28. /** @var int 默认批量处理数量 */
  29. const DEFAULT_BATCH_SIZE = 100;
  30. /** @var int 最大批量处理数量 */
  31. const MAX_BATCH_SIZE = 1000;
  32. /**
  33. * 订单完成后检查并分发抽奖机会(单个活动版本)
  34. * 查询一个正在进行的活动,返回单个结果
  35. *
  36. * @param array $orderInfo 订单信息 ['id', 'total_amount', 'goods' => [['goods_id']]]
  37. * @param int $userId 用户ID
  38. * @return array|null 获得的抽奖机会信息,如果没有则返回null
  39. * @throws Exception
  40. */
  41. public static function checkAndGrantChanceForOrderOne($orderInfo, $userId)
  42. {
  43. if (empty($orderInfo) || empty($userId)) {
  44. throw new BusinessException('订单信息或用户ID不能为空');
  45. }
  46. // try {
  47. // 获取当前正在进行的单个抽奖活动
  48. $activity = LotteryActivityService::getCurrentRunningActivity();
  49. // 如果没有正在进行的活动,返回null
  50. if (!$activity) {
  51. return null;
  52. }
  53. // 处理当前活动
  54. $chances = static::processActivityForOrder($activity, $orderInfo, $userId);
  55. if ($chances > 0) {
  56. return [
  57. 'lottery_id' => $activity->id,
  58. 'lottery_name' => $activity->name,
  59. 'chances' => $chances,
  60. 'granted_time' => time()
  61. ];
  62. }
  63. return null;
  64. // } catch (Exception $e) {
  65. // trace("订单抽奖机会分发失败 - 用户ID: {$userId}, 错误: " . $e->getMessage(), 'error');
  66. // throw new BusinessException('订单抽奖机会分发失败');
  67. // }
  68. }
  69. /**
  70. * 订单完成后检查并分发抽奖机会 多个的
  71. * @param array $orderInfo 订单信息 ['id', 'total_amount', 'goods' => [['goods_id']]]
  72. * @param int $userId 用户ID
  73. * @return array 获得的抽奖机会信息
  74. * @throws Exception
  75. */
  76. public static function checkAndGrantChanceForOrder($orderInfo, $userId)
  77. {
  78. if (empty($orderInfo) || empty($userId)) {
  79. throw new BusinessException('订单信息或用户ID不能为空');
  80. }
  81. $grantedChances = [];
  82. try {
  83. // 获取所有正在进行的抽奖活动 一段时间 有且只有一个抽奖活动
  84. $activities = LotteryActivityService::getRunningActivities();
  85. foreach ($activities as $activity) {
  86. try {
  87. $chances = static::processActivityForOrder($activity, $orderInfo, $userId);
  88. if ($chances > 0) {
  89. $grantedChances[] = [
  90. 'activity_id' => $activity->id,
  91. 'activity_name' => $activity->name,
  92. 'chances' => $chances,
  93. 'granted_time' => time()
  94. ];
  95. }
  96. } catch (Exception $e) {
  97. // 记录错误但不影响其他活动的处理
  98. trace("抽奖机会分发失败 - 活动ID: {$activity->id}, 用户ID: {$userId}, 错误: " . $e->getMessage(), 'error');
  99. }
  100. }
  101. } catch (Exception $e) {
  102. trace("订单抽奖机会分发失败 - 用户ID: {$userId}, 错误: " . $e->getMessage(), 'error');
  103. throw $e;
  104. }
  105. return $grantedChances;
  106. }
  107. /**
  108. * 充值完成后检查并分发抽奖机会(单个活动版本)
  109. * 查询一个正在进行的活动,返回单个结果
  110. *
  111. * @param array $rechargeInfo 充值信息 ['amount', 'type' => 'recharge']
  112. * @param int $userId 用户ID
  113. * @return array|null 获得的抽奖机会信息,如果没有则返回null
  114. * @throws Exception
  115. */
  116. public static function checkAndGrantChanceForRechargeOne($rechargeInfo, $userId)
  117. {
  118. if (empty($rechargeInfo) || empty($userId)) {
  119. throw new Exception('充值信息或用户ID不能为空');
  120. }
  121. try {
  122. // 获取当前正在进行的单个抽奖活动
  123. $activity = LotteryActivityService::getCurrentRunningActivity();
  124. // 如果没有正在进行的活动,返回null
  125. if (!$activity) {
  126. return null;
  127. }
  128. // 处理当前活动
  129. $chances = static::processActivityForRecharge($activity, $rechargeInfo, $userId);
  130. if ($chances > 0) {
  131. return [
  132. 'activity_id' => $activity->id,
  133. 'activity_name' => $activity->name,
  134. 'chances' => $chances,
  135. 'granted_time' => time()
  136. ];
  137. }
  138. return null;
  139. } catch (Exception $e) {
  140. trace("充值抽奖机会分发失败 - 用户ID: {$userId}, 错误: " . $e->getMessage(), 'error');
  141. throw $e;
  142. }
  143. }
  144. /**
  145. * 充值完成后检查并分发抽奖机会(多个活动版本)
  146. *
  147. * @param array $rechargeInfo 充值信息 ['amount', 'type' => 'recharge']
  148. * @param int $userId 用户ID
  149. * @return array 获得的抽奖机会信息
  150. * @throws Exception
  151. */
  152. public static function checkAndGrantChanceForRecharge($rechargeInfo, $userId)
  153. {
  154. if (empty($rechargeInfo) || empty($userId)) {
  155. throw new Exception('充值信息或用户ID不能为空');
  156. }
  157. $grantedChances = [];
  158. try {
  159. // 获取所有正在进行的抽奖活动
  160. $activities = LotteryActivityService::getRunningActivities();
  161. foreach ($activities as $activity) {
  162. try {
  163. $chances = static::processActivityForRecharge($activity, $rechargeInfo, $userId);
  164. if ($chances > 0) {
  165. $grantedChances[] = [
  166. 'activity_id' => $activity->id,
  167. 'activity_name' => $activity->name,
  168. 'chances' => $chances,
  169. 'granted_time' => time()
  170. ];
  171. }
  172. } catch (Exception $e) {
  173. // 记录错误但不影响其他活动的处理
  174. trace("充值抽奖机会分发失败 - 活动ID: {$activity->id}, 用户ID: {$userId}, 错误: " . $e->getMessage(), 'error');
  175. }
  176. }
  177. } catch (Exception $e) {
  178. trace("充值抽奖机会分发失败 - 用户ID: {$userId}, 错误: " . $e->getMessage(), 'error');
  179. throw $e;
  180. }
  181. return $grantedChances;
  182. }
  183. /**
  184. * 手动给用户增加抽奖机会(管理员操作) *
  185. * @param int $activityId 活动ID
  186. * @param int $userId 用户ID
  187. * @param int $chances 机会次数
  188. * @param string $reason 原因
  189. * @param int $adminId 管理员ID
  190. * @return bool
  191. * @throws Exception
  192. */
  193. public static function manualGrantChance($activityId, $userId, $chances, $reason = '', $adminId = 0)
  194. {
  195. if ($chances <= 0) {
  196. throw new Exception('抽奖机会数量必须大于0');
  197. }
  198. $activity = LotteryActivity::find($activityId);
  199. if (!$activity) {
  200. throw new Exception('活动不存在');
  201. }
  202. $user = User::find($userId);
  203. if (!$user) {
  204. throw new Exception('用户不存在');
  205. }
  206. $detail = [
  207. 'reason' => $reason,
  208. 'admin_id' => $adminId,
  209. 'granted_time' => time()
  210. ];
  211. return static::grantChanceToUser($activityId, $userId, $chances, $detail);
  212. }
  213. /**
  214. * 批量初始化用户抽奖机会(活动开始时)
  215. *
  216. * @param int $activityId 活动ID
  217. * @param array $userIds 用户ID数组
  218. * @param int $initChances 初始机会数
  219. * @param int $batchSize 批量处理大小
  220. * @return array 处理结果
  221. * @throws Exception
  222. */
  223. public static function batchInitChances($activityId, $userIds, $initChances = 1, $batchSize = null)
  224. {
  225. if (empty($userIds)) {
  226. throw new Exception('用户ID列表不能为空');
  227. }
  228. $activity = LotteryActivity::find($activityId);
  229. if (!$activity) {
  230. throw new Exception('活动不存在');
  231. }
  232. $batchSize = $batchSize ?: static::DEFAULT_BATCH_SIZE;
  233. $batchSize = min($batchSize, static::MAX_BATCH_SIZE);
  234. $result = [
  235. 'total_users' => count($userIds),
  236. 'success_count' => 0,
  237. 'failed_count' => 0,
  238. 'errors' => []
  239. ];
  240. // 分批处理
  241. $batches = array_chunk($userIds, $batchSize);
  242. foreach ($batches as $batch) {
  243. try {
  244. $success = static::batchCreateChances($activityId, $batch, $initChances);
  245. if ($success) {
  246. $result['success_count'] += count($batch);
  247. } else {
  248. $result['failed_count'] += count($batch);
  249. $result['errors'][] = "批次处理失败: " . implode(',', $batch);
  250. }
  251. } catch (Exception $e) {
  252. $result['failed_count'] += count($batch);
  253. $result['errors'][] = "批次处理异常: " . $e->getMessage();
  254. }
  255. }
  256. return $result;
  257. }
  258. // ============ 私有处理方法 ============
  259. /**
  260. * 处理订单相关的活动
  261. *
  262. * @param LotteryActivity $activity 活动对象
  263. * @param array $orderInfo 订单信息
  264. * @param int $userId 用户ID
  265. * @return int 获得的抽奖机会数量
  266. */
  267. private static function processActivityForOrder($activity, $orderInfo, $userId)
  268. {
  269. // 检查用户是否符合活动参与资格
  270. if (!static::checkUserQualification($activity, $userId)) {
  271. return 0;
  272. }
  273. // 获取活动的参与条件
  274. $conditions = static::getValidConditions($activity->id);
  275. $totalChances = 0;
  276. $chanceDetails = [];
  277. foreach ($conditions as $condition) {
  278. // 跳过充值条件
  279. if ($condition->type == LotteryEnum::CONDITION_TYPE_RECHARGE_AMOUNT) {
  280. continue;
  281. }
  282. $result = static::processConditionForOrder($condition, $orderInfo, $userId);
  283. if ($result['chances'] > 0) {
  284. $totalChances += $result['chances'];
  285. $result['detail']['chances'] = $result['chances'];
  286. $chanceDetails[] = $result['detail'];
  287. }
  288. }
  289. // 如果获得了抽奖机会,记录到数据库
  290. if ($totalChances > 0) {
  291. // 为每个条件分别记录
  292. foreach ($chanceDetails as $detail) {
  293. static::grantChanceToUser($activity->id, $userId, $detail['chances'] ?? 1, [
  294. 'condition_id' => $detail['condition_id'],
  295. 'condition_type' => $detail['condition_type'],
  296. 'condition_value' => $detail['condition_value'],
  297. 'order_id' => $orderInfo['id'] ?? 0,
  298. 'granted_time' => time()
  299. ]);
  300. }
  301. }
  302. return $totalChances;
  303. }
  304. /**
  305. * 处理充值相关的活动
  306. *
  307. * @param LotteryActivity $activity 活动对象
  308. * @param array $rechargeInfo 充值信息
  309. * @param int $userId 用户ID
  310. * @return int 获得的抽奖机会数量
  311. */
  312. private static function processActivityForRecharge($activity, $rechargeInfo, $userId)
  313. {
  314. // 检查用户是否符合活动参与资格
  315. if (!static::checkUserQualification($activity, $userId)) {
  316. return 0;
  317. }
  318. // 获取活动的参与条件
  319. $conditions = static::getValidConditions($activity->id);
  320. $totalChances = 0;
  321. $chanceDetails = [];
  322. foreach ($conditions as $condition) {
  323. // 只处理充值条件
  324. if ($condition->type != LotteryEnum::CONDITION_TYPE_RECHARGE_AMOUNT) {
  325. continue;
  326. }
  327. $result = static::processConditionForRecharge($condition, $rechargeInfo, $userId);
  328. if ($result['chances'] > 0) {
  329. $totalChances += $result['chances'];
  330. $result['detail']['chances'] = $result['chances'];
  331. $chanceDetails[] = $result['detail'];
  332. }
  333. }
  334. // 如果获得了抽奖机会,记录到数据库
  335. if ($totalChances > 0) {
  336. // 为每个条件分别记录
  337. foreach ($chanceDetails as $detail) {
  338. static::grantChanceToUser($activity->id, $userId, $detail['chances'] ?? 1, [
  339. 'condition_id' => $detail['condition_id'],
  340. 'condition_type' => $detail['condition_type'],
  341. 'condition_value' => $detail['condition_value'],
  342. 'recharge_amount' => $rechargeInfo['amount'] ?? 0,
  343. 'granted_time' => time()
  344. ]);
  345. }
  346. }
  347. return $totalChances;
  348. }
  349. /**
  350. * 处理订单条件
  351. *
  352. * @param LotteryCondition $condition 条件对象
  353. * @param array $orderInfo 订单信息
  354. * @param int $userId 用户ID
  355. * @return array 获得的抽奖机会信息 ['chances' => int, 'detail' => array]
  356. */
  357. private static function processConditionForOrder($condition, $orderInfo, $userId)
  358. {
  359. $chances = 0;
  360. $detail = [
  361. 'condition_id' => $condition->id,
  362. 'condition_type' => $condition->type,
  363. 'condition_value' => $condition->condition_value,
  364. ];
  365. switch ($condition->type) {
  366. case LotteryEnum::CONDITION_TYPE_BUY_GOODS:
  367. if (static::validateGoodsCondition($condition, $orderInfo)) {
  368. $chances = static::getRewardTimes($condition);
  369. }
  370. break;
  371. case LotteryEnum::CONDITION_TYPE_ORDER_AMOUNT:
  372. if (static::validateOrderAmountCondition($condition, $orderInfo)) {
  373. $chances = static::getRewardTimes($condition);
  374. // 如果可重复获得,根据金额倍数计算次数
  375. if (static::canRepeat($condition)) {
  376. // 使用bcdiv进行精确的金额除法运算,然后取整
  377. $multiple = floor(bcdiv($orderInfo['total_amount'], $condition->condition_value, 2));
  378. $chances *= $multiple;
  379. }
  380. }
  381. break;
  382. case LotteryEnum::CONDITION_TYPE_TOTAL_AMOUNT:
  383. if (static::validateAccumulateCondition($condition, $userId, $condition->activity_id)) {
  384. // 检查是否已经因为累计消费获得过机会
  385. if (!static::hasGrantedForAccumulate($condition->activity_id, $userId)) {
  386. $chances = static::getRewardTimes($condition);
  387. }
  388. }
  389. break;
  390. }
  391. return [
  392. 'chances' => $chances,
  393. 'detail' => $detail
  394. ];
  395. }
  396. /**
  397. * 处理充值条件
  398. *
  399. * @param LotteryCondition $condition 条件对象
  400. * @param array $rechargeInfo 充值信息
  401. * @param int $userId 用户ID
  402. * @return array 获得的抽奖机会信息 ['chances' => int, 'detail' => array]
  403. */
  404. private static function processConditionForRecharge($condition, $rechargeInfo, $userId)
  405. {
  406. $chances = 0;
  407. $detail = [
  408. 'condition_id' => $condition->id,
  409. 'condition_type' => $condition->type,
  410. 'condition_value' => $condition->condition_value,
  411. ];
  412. if (static::validateRechargeCondition($condition, ['type' => 'recharge', 'amount' => $rechargeInfo['amount']])) {
  413. $chances = static::getRewardTimes($condition);
  414. // 如果可重复获得,根据金额倍数计算次数
  415. if (static::canRepeat($condition)) {
  416. // 使用bcdiv进行精确的金额除法运算,然后取整
  417. $multiple = floor(bcdiv($rechargeInfo['amount'], $condition->condition_value, 2));
  418. $chances *= $multiple;
  419. }
  420. }
  421. return [
  422. 'chances' => $chances,
  423. 'detail' => $detail
  424. ];
  425. }
  426. // ============ 用户资格检查方法 ============
  427. /**
  428. * 检查用户资格
  429. *
  430. * @param LotteryActivity $activity 活动对象
  431. * @param int $userId 用户ID
  432. * @return bool
  433. */
  434. private static function checkUserQualification($activity, $userId)
  435. {
  436. // 检查用户群体限制
  437. switch ($activity->user_limit_type) {
  438. case LotteryEnum::USER_LIMIT_ALL:
  439. return true;
  440. case LotteryEnum::USER_LIMIT_LEVEL:
  441. return static::checkUserLevel($userId, $activity->user_limit_value);
  442. case LotteryEnum::USER_LIMIT_TAG:
  443. return static::checkUserTag($userId, $activity->user_limit_value);
  444. default:
  445. return false;
  446. }
  447. }
  448. /**
  449. * 检查用户等级
  450. *
  451. * @param int $userId 用户ID
  452. * @param mixed $limitValue 限制值
  453. * @return bool
  454. */
  455. private static function checkUserLevel($userId, $limitValue)
  456. {
  457. if (empty($limitValue)) {
  458. return true;
  459. }
  460. $user = User::find($userId);
  461. if (!$user) {
  462. return false;
  463. }
  464. $limitLevels = is_array($limitValue) ? $limitValue : [$limitValue];
  465. return in_array($user->level, $limitLevels);
  466. }
  467. /**
  468. * 检查用户标签
  469. *
  470. * @param int $userId 用户ID
  471. * @param mixed $limitValue 限制值
  472. * @return bool
  473. */
  474. private static function checkUserTag($userId, $limitValue)
  475. {
  476. if (empty($limitValue)) {
  477. return true;
  478. }
  479. // TODO: 根据实际的用户标签系统实现
  480. // 这里需要根据具体的用户标签表结构来实现
  481. // 暂时返回true,避免影响现有功能
  482. return true;
  483. }
  484. /**
  485. * 检查是否已因累计消费获得过机会
  486. *
  487. * @param int $activityId 活动ID
  488. * @param int $userId 用户ID
  489. * @return bool
  490. */
  491. private static function hasGrantedForAccumulate($activityId, $userId)
  492. {
  493. $record = LotteryUserChanceRecord::where('activity_id', $activityId)
  494. ->where('user_id', $userId)
  495. ->where('get_type', LotteryEnum::CHANCE_GET_TYPE_TOTAL_AMOUNT)
  496. ->find();
  497. return $record ? true : false;
  498. }
  499. // ============ 条件验证方法 ============
  500. /**
  501. * 验证订单是否满足条件
  502. *
  503. * @param LotteryCondition $condition 条件对象
  504. * @param array $orderInfo 订单信息
  505. * @return bool
  506. */
  507. public static function validateOrder(LotteryCondition $condition, $orderInfo)
  508. {
  509. switch ($condition->type) {
  510. case LotteryEnum::CONDITION_TYPE_BUY_GOODS:
  511. return static::validateGoodsCondition($condition, $orderInfo);
  512. case LotteryEnum::CONDITION_TYPE_ORDER_AMOUNT:
  513. return static::validateOrderAmountCondition($condition, $orderInfo);
  514. case LotteryEnum::CONDITION_TYPE_RECHARGE_AMOUNT:
  515. return static::validateRechargeCondition($condition, $orderInfo);
  516. default:
  517. return false;
  518. }
  519. }
  520. /**
  521. * 验证商品条件
  522. *
  523. * @param LotteryCondition $condition 条件对象
  524. * @param array $orderInfo 订单信息
  525. * @return bool
  526. */
  527. public static function validateGoodsCondition(LotteryCondition $condition, $orderInfo)
  528. {
  529. if (empty($orderInfo['goods']) || empty($condition->goods_ids_list)) {
  530. return false;
  531. }
  532. $orderGoodsIds = array_column($orderInfo['goods'], 'goods_id');
  533. $conditionGoodsIds = $condition->goods_ids_list;
  534. $intersection = array_intersect($orderGoodsIds, $conditionGoodsIds);
  535. if ($condition->goods_rule == LotteryEnum::GOODS_RULE_INCLUDE) {
  536. // 指定商品参与:订单中必须包含指定商品
  537. return !empty($intersection);
  538. } else {
  539. // 指定商品不可参与:订单中不能包含指定商品
  540. return empty($intersection);
  541. }
  542. }
  543. /**
  544. * 验证订单金额条件
  545. *
  546. * @param LotteryCondition $condition 条件对象
  547. * @param array $orderInfo 订单信息
  548. * @return bool
  549. */
  550. public static function validateOrderAmountCondition(LotteryCondition $condition, $orderInfo)
  551. {
  552. $orderAmount = $orderInfo['total_amount'] ?? 0;
  553. // 使用bccomp进行精确的金额比较,返回值:-1(小于)、0(等于)、1(大于)
  554. return bccomp($orderAmount, $condition->condition_value, 2) >= 0;
  555. }
  556. /**
  557. * 验证充值条件
  558. *
  559. * @param LotteryCondition $condition 条件对象
  560. * @param array $orderInfo 订单信息
  561. * @return bool
  562. */
  563. public static function validateRechargeCondition(LotteryCondition $condition, $orderInfo)
  564. {
  565. if (($orderInfo['type'] ?? '') !== 'recharge') {
  566. return false;
  567. }
  568. $rechargeAmount = $orderInfo['amount'] ?? 0;
  569. // 使用bccomp进行精确的金额比较
  570. return bccomp($rechargeAmount, $condition->condition_value, 2) >= 0;
  571. }
  572. /**
  573. * 验证累计消费条件
  574. *
  575. * @param LotteryCondition $condition 条件对象
  576. * @param int $userId 用户ID
  577. * @param int $activityId 活动ID
  578. * @return bool
  579. */
  580. public static function validateAccumulateCondition(LotteryCondition $condition, $userId, $activityId)
  581. {
  582. $activity = LotteryActivity::find($activityId);
  583. if (!$activity) {
  584. return false;
  585. }
  586. // 计算活动期间用户累计消费
  587. $totalAmount = Order::where('user_id', $userId)
  588. ->where('order_status', OrderEnum::STATUS_PAY)
  589. ->where('pay_time', '>=', $activity->start_time)
  590. ->where('pay_time', '<=', $activity->end_time)
  591. ->sum('amount');
  592. // 使用bccomp进行精确的金额比较
  593. return bccomp($totalAmount, $condition->condition_value, 2) >= 0;
  594. }
  595. // ============ 条件管理方法 ============
  596. /**
  597. * 获取活动的有效条件
  598. *
  599. * @param int $activityId 活动ID
  600. * @return array
  601. */
  602. public static function getValidConditions($activityId)
  603. {
  604. return LotteryCondition::where('activity_id', $activityId)
  605. ->where('status', 1)
  606. ->order('id', 'asc')
  607. ->select();
  608. }
  609. /**
  610. * 检查条件是否可重复获得奖励
  611. *
  612. * @param LotteryCondition $condition 条件对象
  613. * @return bool
  614. */
  615. public static function canRepeat(LotteryCondition $condition)
  616. {
  617. return $condition->is_repeatable == 1;
  618. }
  619. /**
  620. * 获取奖励次数
  621. *
  622. * @param LotteryCondition $condition 条件对象
  623. * @return int
  624. */
  625. public static function getRewardTimes(LotteryCondition $condition)
  626. {
  627. return $condition->reward_times ?: 1;
  628. }
  629. /**
  630. * 批量验证订单条件
  631. *
  632. * @param int $activityId 活动ID
  633. * @param array $orderInfo 订单信息
  634. * @param int $userId 用户ID
  635. * @return array 满足的条件列表
  636. */
  637. public static function batchValidateConditions($activityId, $orderInfo, $userId)
  638. {
  639. $conditions = static::getValidConditions($activityId);
  640. $validConditions = [];
  641. foreach ($conditions as $condition) {
  642. if (static::validateOrder($condition, $orderInfo)) {
  643. $validConditions[] = [
  644. 'condition_id' => $condition->id,
  645. 'condition_name' => $condition->name,
  646. 'condition_type' => $condition->type,
  647. 'condition_type_text' => $condition->type_text,
  648. 'reward_times' => static::getRewardTimes($condition),
  649. 'can_repeat' => static::canRepeat($condition)
  650. ];
  651. }
  652. }
  653. return $validConditions;
  654. }
  655. /**
  656. * 获取条件统计信息
  657. *
  658. * @param int $activityId 活动ID
  659. * @return array
  660. */
  661. public static function getConditionStatistics($activityId)
  662. {
  663. $conditions = static::getValidConditions($activityId);
  664. $statistics = [
  665. 'total_conditions' => count($conditions),
  666. 'goods_conditions' => 0,
  667. 'amount_conditions' => 0,
  668. 'recharge_conditions' => 0,
  669. 'accumulate_conditions' => 0
  670. ];
  671. foreach ($conditions as $condition) {
  672. switch ($condition->type) {
  673. case LotteryEnum::CONDITION_TYPE_BUY_GOODS:
  674. $statistics['goods_conditions']++;
  675. break;
  676. case LotteryEnum::CONDITION_TYPE_ORDER_AMOUNT:
  677. $statistics['amount_conditions']++;
  678. break;
  679. case LotteryEnum::CONDITION_TYPE_RECHARGE_AMOUNT:
  680. $statistics['recharge_conditions']++;
  681. break;
  682. case LotteryEnum::CONDITION_TYPE_TOTAL_AMOUNT:
  683. $statistics['accumulate_conditions']++;
  684. break;
  685. }
  686. }
  687. return $statistics;
  688. }
  689. // ============ 用户机会管理方法 ============
  690. /**
  691. * 获取用户抽奖机会
  692. *
  693. * @param int $activityId 活动ID
  694. * @param int $userId 用户ID
  695. * @return LotteryUserChance|null
  696. */
  697. public static function getUserChance($activityId, $userId)
  698. {
  699. return LotteryUserChance::where('activity_id', $activityId)
  700. ->where('user_id', $userId)
  701. ->find();
  702. }
  703. /**
  704. * 根据详情确定机会获取类型
  705. *
  706. * @param array $detail 获得详情
  707. * @return int 获取类型
  708. */
  709. private static function getChanceGetTypeFromDetail($detail)
  710. {
  711. // 如果有条件类型,直接使用条件类型对应的获取类型
  712. if (isset($detail['condition_type'])) {
  713. switch ($detail['condition_type']) {
  714. case LotteryEnum::CONDITION_TYPE_BUY_GOODS:
  715. return LotteryEnum::CHANCE_GET_TYPE_BUY_GOODS;
  716. case LotteryEnum::CONDITION_TYPE_ORDER_AMOUNT:
  717. return LotteryEnum::CHANCE_GET_TYPE_ORDER_AMOUNT;
  718. case LotteryEnum::CONDITION_TYPE_RECHARGE_AMOUNT:
  719. return LotteryEnum::CHANCE_GET_TYPE_RECHARGE;
  720. case LotteryEnum::CONDITION_TYPE_TOTAL_AMOUNT:
  721. return LotteryEnum::CHANCE_GET_TYPE_TOTAL_AMOUNT;
  722. }
  723. }
  724. // 如果没有条件类型,检查是否是管理员赠送
  725. if (isset($detail['admin_id']) && $detail['admin_id'] > 0) {
  726. return LotteryEnum::CHANCE_GET_TYPE_ADMIN_GRANT;
  727. }
  728. // 默认返回管理员赠送
  729. return LotteryEnum::CHANCE_GET_TYPE_ADMIN_GRANT;
  730. }
  731. /**
  732. * 获取用户在指定活动中的抽奖机会详情
  733. *
  734. * @param int $activityId 活动ID
  735. * @param int $userId 用户ID
  736. * @return array
  737. */
  738. public static function getUserChanceDetail($activityId, $userId)
  739. {
  740. $userChance = static::getUserChance($activityId, $userId);
  741. if (!$userChance) {
  742. return [
  743. 'total_chances' => 0,
  744. 'used_chances' => 0,
  745. 'remain_chances' => 0,
  746. 'get_records' => []
  747. ];
  748. }
  749. // 获取机会获得记录(使用服务类方法)
  750. $getRecords = static::getUserChanceRecord($userId, $activityId);
  751. return [
  752. 'total_chances' => $userChance->total_chances,
  753. 'used_chances' => $userChance->used_chances,
  754. 'remain_chances' => $userChance->remain_chances,
  755. 'last_get_time' => $userChance->last_get_time,
  756. 'last_use_time' => $userChance->last_use_time,
  757. 'get_records' => $getRecords
  758. ];
  759. }
  760. /**
  761. * 给用户分发抽奖机会
  762. *
  763. * @param int $activityId 活动ID
  764. * @param int $userId 用户ID
  765. * @param int $chances 机会次数
  766. * @param array $detail 获得详情
  767. * @return LotteryUserChance|bool
  768. */
  769. private static function grantChanceToUser($activityId, $userId, $chances, $detail)
  770. {
  771. return static::addChance($activityId, $userId, $chances, $detail);
  772. }
  773. /**
  774. * 增加抽奖机会
  775. *
  776. * @param int $activityId 活动ID
  777. * @param int $userId 用户ID
  778. * @param int $times 机会次数
  779. * @param array $detail 获得详情
  780. * @return LotteryUserChance|bool
  781. */
  782. public static function addChance($activityId, $userId, $times = 1, $detail = [])
  783. {
  784. if ($times <= 0) {
  785. return false;
  786. }
  787. try {
  788. Db::startTrans();
  789. $chance = static::getUserChance($activityId, $userId);
  790. if (!$chance) {
  791. // 创建新记录
  792. $data = [
  793. 'activity_id' => $activityId,
  794. 'user_id' => $userId,
  795. 'total_chances' => $times,
  796. 'used_chances' => 0,
  797. 'remain_chances' => $times,
  798. 'last_get_time' => time(),
  799. 'get_detail' => json_encode([]) // 保留字段但不使用
  800. ];
  801. $chance = LotteryUserChance::create($data);
  802. } else {
  803. // 更新现有记录
  804. $chance->total_chances += $times;
  805. $chance->remain_chances += $times;
  806. $chance->last_get_time = time();
  807. $chance->save();
  808. }
  809. // 创建获得记录
  810. $recordData = [
  811. 'activity_id' => $activityId,
  812. 'user_id' => $userId,
  813. 'get_type' => static::getChanceGetTypeFromDetail($detail),
  814. 'chances' => $times,
  815. 'condition_id' => $detail['condition_id'] ?? null,
  816. 'condition_value' => $detail['condition_value'] ?? null,
  817. 'order_id' => $detail['order_id'] ?? null,
  818. 'recharge_amount' => $detail['recharge_amount'] ?? null,
  819. 'admin_id' => $detail['admin_id'] ?? null,
  820. 'reason' => $detail['reason'] ?? null,
  821. 'remark' => $detail['remark'] ?? null,
  822. 'get_time' => time()
  823. ];
  824. $validation = LotteryUserChanceRecord::validateRecord($recordData);
  825. if ($validation !== true) {
  826. throw new Exception($validation);
  827. }
  828. LotteryUserChanceRecord::create($recordData);
  829. Db::commit();
  830. return $chance;
  831. } catch (Exception $e) {
  832. Db::rollback();
  833. throw $e;
  834. }
  835. }
  836. /**
  837. * 使用抽奖机会
  838. *
  839. * @param LotteryUserChance $userChance 用户机会对象
  840. * @param int $times 使用次数
  841. * @return bool
  842. */
  843. public static function useChance(LotteryUserChance $userChance, $times = 1)
  844. {
  845. if ($userChance->remain_chances < $times) {
  846. return false;
  847. }
  848. $userChance->used_chances += $times;
  849. $userChance->remain_chances -= $times;
  850. $userChance->last_use_time = time();
  851. return $userChance->save();
  852. }
  853. /**
  854. * 检查是否有剩余机会
  855. *
  856. * @param LotteryUserChance $userChance 用户机会对象
  857. * @param int $times 需要的机会次数
  858. * @return bool
  859. */
  860. public static function hasChance(LotteryUserChance $userChance, $times = 1)
  861. {
  862. return $userChance->remain_chances >= $times;
  863. }
  864. /**
  865. * 重置抽奖机会(用于测试或特殊情况)
  866. *
  867. * @param LotteryUserChance $userChance 用户机会对象
  868. * @return bool
  869. */
  870. public static function resetChance(LotteryUserChance $userChance)
  871. {
  872. $userChance->used_chances = 0;
  873. $userChance->remain_chances = $userChance->total_chances;
  874. return $userChance->save();
  875. }
  876. // ============ 统计和查询方法 ============
  877. /**
  878. * 获取活动总参与人数
  879. *
  880. * @param int $activityId 活动ID
  881. * @return int
  882. */
  883. public static function getActivityParticipants($activityId)
  884. {
  885. return LotteryUserChance::where('activity_id', $activityId)->count();
  886. }
  887. /**
  888. * 获取用户在多个活动中的机会统计
  889. *
  890. * @param int $userId 用户ID
  891. * @param array $activityIds 活动ID数组
  892. * @return array
  893. */
  894. public static function getUserChancesStats($userId, $activityIds = [])
  895. {
  896. $query = LotteryUserChance::where('user_id', $userId);
  897. if (!empty($activityIds)) {
  898. $query->where('activity_id', 'in', $activityIds);
  899. }
  900. return $query->field([
  901. 'activity_id',
  902. 'total_chances',
  903. 'used_chances',
  904. 'remain_chances'
  905. ])
  906. ->select();
  907. }
  908. /**
  909. * 获取用户在所有活动中的机会概览
  910. *
  911. * @param int $userId 用户ID
  912. * @return array
  913. */
  914. public static function getUserAllChancesOverview($userId)
  915. {
  916. $chances = LotteryUserChance::where('user_id', $userId)
  917. ->with(['activity'])
  918. ->select();
  919. $overview = [
  920. 'total_activities' => count($chances),
  921. 'total_chances' => 0,
  922. 'total_used' => 0,
  923. 'total_remain' => 0,
  924. 'activities' => []
  925. ];
  926. foreach ($chances as $chance) {
  927. $overview['total_chances'] += $chance->total_chances;
  928. $overview['total_used'] += $chance->used_chances;
  929. $overview['total_remain'] += $chance->remain_chances;
  930. $overview['activities'][] = [
  931. 'activity_id' => $chance->activity_id,
  932. 'activity_name' => $chance->activity->name ?? '',
  933. 'total_chances' => $chance->total_chances,
  934. 'used_chances' => $chance->used_chances,
  935. 'remain_chances' => $chance->remain_chances,
  936. 'last_get_time' => $chance->last_get_time,
  937. 'last_use_time' => $chance->last_use_time
  938. ];
  939. }
  940. return $overview;
  941. }
  942. /**
  943. * 检查用户是否可以参与活动
  944. *
  945. * @param int $activityId 活动ID
  946. * @param int $userId 用户ID
  947. * @return bool
  948. */
  949. public static function canUserParticipate($activityId, $userId)
  950. {
  951. $userChance = static::getUserChance($activityId, $userId);
  952. return $userChance && static::hasChance($userChance, 1);
  953. }
  954. /**
  955. * 获取活动参与用户列表
  956. *
  957. * @param int $activityId 活动ID
  958. * @param int $page 页码
  959. * @param int $limit 每页数量
  960. * @return array
  961. */
  962. public static function getActivityParticipantsList($activityId, $page = 1, $limit = 20)
  963. {
  964. return LotteryUserChance::where('activity_id', $activityId)
  965. ->with(['user'])
  966. ->order('createtime', 'desc')
  967. ->page($page, $limit)
  968. ->select();
  969. }
  970. /**
  971. * 获取活动参与统计
  972. *
  973. * @param int $activityId 活动ID
  974. * @return array
  975. */
  976. public static function getActivityParticipationStats($activityId)
  977. {
  978. $stats = LotteryUserChance::where('activity_id', $activityId)
  979. ->field([
  980. 'COUNT(*) as total_participants',
  981. 'SUM(total_chances) as total_chances_granted',
  982. 'SUM(used_chances) as total_chances_used',
  983. 'SUM(remain_chances) as total_chances_remain'
  984. ])
  985. ->find();
  986. return [
  987. 'total_participants' => $stats['total_participants'] ?? 0,
  988. 'total_chances_granted' => $stats['total_chances_granted'] ?? 0,
  989. 'total_chances_used' => $stats['total_chances_used'] ?? 0,
  990. 'total_chances_remain' => $stats['total_chances_remain'] ?? 0,
  991. 'usage_rate' => $stats['total_chances_granted'] > 0 ?
  992. round(($stats['total_chances_used'] / $stats['total_chances_granted']) * 100, 2) : 0
  993. ];
  994. }
  995. // ============ 批量操作方法 ============
  996. /**
  997. * 批量创建用户机会(用于活动启动时)
  998. *
  999. * @param int $activityId 活动ID
  1000. * @param array $userIds 用户ID数组
  1001. * @param int $times 机会次数
  1002. * @return bool
  1003. */
  1004. public static function batchCreateChances($activityId, $userIds, $times = 1)
  1005. {
  1006. if (empty($userIds)) {
  1007. return false;
  1008. }
  1009. $data = [];
  1010. $now = time();
  1011. foreach ($userIds as $userId) {
  1012. $data[] = [
  1013. 'activity_id' => $activityId,
  1014. 'user_id' => $userId,
  1015. 'total_chances' => $times,
  1016. 'used_chances' => 0,
  1017. 'remain_chances' => $times,
  1018. 'last_get_time' => $now,
  1019. 'createtime' => $now,
  1020. 'updatetime' => $now
  1021. ];
  1022. }
  1023. return LotteryUserChance::insertAll($data);
  1024. }
  1025. /**
  1026. * 批量检查用户资格
  1027. *
  1028. * @param int $activityId 活动ID
  1029. * @param array $userIds 用户ID数组
  1030. * @return array 符合条件的用户ID数组
  1031. */
  1032. public static function batchCheckUserQualification($activityId, $userIds)
  1033. {
  1034. $activity = LotteryActivity::find($activityId);
  1035. if (!$activity) {
  1036. return [];
  1037. }
  1038. $qualifiedUsers = [];
  1039. foreach ($userIds as $userId) {
  1040. if (static::checkUserQualification($activity, $userId)) {
  1041. $qualifiedUsers[] = $userId;
  1042. }
  1043. }
  1044. return $qualifiedUsers;
  1045. }
  1046. /**
  1047. * 批量验证条件
  1048. *
  1049. * @param int $activityId 活动ID
  1050. * @param array $orderInfo 订单信息
  1051. * @param array $userIds 用户ID数组
  1052. * @return array 每个用户满足的条件
  1053. */
  1054. public static function batchValidateConditionsForUsers($activityId, $orderInfo, $userIds)
  1055. {
  1056. $results = [];
  1057. foreach ($userIds as $userId) {
  1058. $results[$userId] = static::batchValidateConditions($activityId, $orderInfo, $userId);
  1059. }
  1060. return $results;
  1061. }
  1062. // ============ 机会获取记录管理方法 ============
  1063. /**
  1064. * 获取用户机会获取记录
  1065. *
  1066. * @param int $activityId 活动ID
  1067. * @param int $userId 用户ID
  1068. * @param int $page 页码
  1069. * @param int $limit 每页数量
  1070. * @return array
  1071. */
  1072. public static function getUserChanceRecords($activityId, $userId, $page = 1, $limit = 20)
  1073. {
  1074. return LotteryUserChanceRecord::where('activity_id', $activityId)
  1075. ->where('user_id', $userId)
  1076. ->with(['condition', 'order', 'admin'])
  1077. ->order('get_time desc')
  1078. ->page($page, $limit)
  1079. ->select();
  1080. }
  1081. /**
  1082. * 获取活动机会获取统计
  1083. *
  1084. * @param int $activityId 活动ID
  1085. * @return array
  1086. */
  1087. public static function getActivityChanceRecordStats($activityId)
  1088. {
  1089. $records = LotteryUserChanceRecord::where('activity_id', $activityId)->select();
  1090. $stats = [
  1091. 'total_records' => count($records),
  1092. 'total_chances' => 0,
  1093. 'type_stats' => [],
  1094. ];
  1095. foreach ($records as $record) {
  1096. $stats['total_chances'] += $record->chances;
  1097. $getType = $record->get_type;
  1098. if (!isset($stats['type_stats'][$getType])) {
  1099. $stats['type_stats'][$getType] = [
  1100. 'type' => $getType,
  1101. 'type_text' => LotteryEnum::getChanceGetTypeText($getType),
  1102. 'count' => 0,
  1103. 'chances' => 0,
  1104. ];
  1105. }
  1106. $stats['type_stats'][$getType]['count']++;
  1107. $stats['type_stats'][$getType]['chances'] += $record->chances;
  1108. }
  1109. return $stats;
  1110. }
  1111. /**
  1112. * 获取用户机会获取统计
  1113. *
  1114. * @param int $userId 用户ID
  1115. * @param int $activityId 活动ID(可选)
  1116. * @return array
  1117. */
  1118. public static function getUserChanceRecord($userId, $activityId = null)
  1119. {
  1120. $query = LotteryUserChanceRecord::where('user_id', $userId);
  1121. if ($activityId) {
  1122. $query->where('activity_id', $activityId);
  1123. }
  1124. $records = $query->select();
  1125. $stats = [
  1126. 'total_records' => count($records),
  1127. 'total_chances' => 0,
  1128. 'type_stats' => [],
  1129. 'recent_records' => [],
  1130. ];
  1131. foreach ($records as $record) {
  1132. $stats['total_chances'] += $record->chances;
  1133. $getType = $record->get_type;
  1134. if (!isset($stats['type_stats'][$getType])) {
  1135. $stats['type_stats'][$getType] = [
  1136. 'type' => $getType,
  1137. 'type_text' => LotteryEnum::getChanceGetTypeText($getType),
  1138. 'count' => 0,
  1139. 'chances' => 0,
  1140. ];
  1141. }
  1142. $stats['type_stats'][$getType]['count']++;
  1143. $stats['type_stats'][$getType]['chances'] += $record->chances;
  1144. }
  1145. // 获取最近的记录
  1146. $stats['recent_records'] = LotteryUserChanceRecord::where('user_id', $userId)
  1147. ->with(['activity'])
  1148. ->order('get_time desc')
  1149. ->limit(5)
  1150. ->select();
  1151. return $stats;
  1152. }
  1153. /**
  1154. * 批量创建机会获取记录
  1155. *
  1156. * @param array $records 记录数组
  1157. * @return bool
  1158. */
  1159. public static function batchCreateChanceRecords($records)
  1160. {
  1161. if (empty($records)) {
  1162. return false;
  1163. }
  1164. // 为每条记录添加创建时间
  1165. foreach ($records as &$record) {
  1166. $record['createtime'] = time();
  1167. $record['get_time'] = $record['get_time'] ?? time();
  1168. }
  1169. return LotteryUserChanceRecord::insertAll($records);
  1170. }
  1171. /**
  1172. * 验证机会获取记录数据
  1173. *
  1174. * @param array $data 记录数据
  1175. * @return bool|string true表示验证通过,string表示错误信息
  1176. */
  1177. public static function validateChanceRecord($data)
  1178. {
  1179. // 验证必填字段
  1180. if (empty($data['activity_id'])) {
  1181. return '活动ID不能为空';
  1182. }
  1183. if (empty($data['user_id'])) {
  1184. return '用户ID不能为空';
  1185. }
  1186. if (empty($data['get_type'])) {
  1187. return '获取类型不能为空';
  1188. }
  1189. if (empty($data['chances']) || $data['chances'] <= 0) {
  1190. return '机会次数必须大于0';
  1191. }
  1192. // 验证获取类型是否有效
  1193. if (!LotteryEnum::isValidChanceGetType($data['get_type'])) {
  1194. return '无效的获取类型';
  1195. }
  1196. // 根据获取类型验证相关字段
  1197. switch ($data['get_type']) {
  1198. case LotteryEnum::CHANCE_GET_TYPE_BUY_GOODS:
  1199. case LotteryEnum::CHANCE_GET_TYPE_ORDER_AMOUNT:
  1200. if (empty($data['order_id'])) {
  1201. return '订单ID不能为空';
  1202. }
  1203. break;
  1204. case LotteryEnum::CHANCE_GET_TYPE_RECHARGE:
  1205. if (empty($data['recharge_amount']) || $data['recharge_amount'] <= 0) {
  1206. return '充值金额必须大于0';
  1207. }
  1208. break;
  1209. case LotteryEnum::CHANCE_GET_TYPE_ADMIN_GRANT:
  1210. if (empty($data['admin_id'])) {
  1211. return '管理员ID不能为空';
  1212. }
  1213. break;
  1214. }
  1215. return true;
  1216. }
  1217. /**
  1218. * 创建单条机会获取记录
  1219. *
  1220. * @param array $data 记录数据
  1221. * @return bool|int 成功返回记录ID,失败返回false
  1222. */
  1223. public static function createChanceRecord($data)
  1224. {
  1225. // 验证数据
  1226. $validation = static::validateChanceRecord($data);
  1227. if ($validation !== true) {
  1228. throw new BusinessException($validation);
  1229. }
  1230. // 设置默认值
  1231. $data['createtime'] = time();
  1232. $data['get_time'] = $data['get_time'] ?? time();
  1233. $record = new LotteryUserChanceRecord($data);
  1234. if ($record->save()) {
  1235. return $record->id;
  1236. }
  1237. return false;
  1238. }
  1239. /**
  1240. * 获取用户在某个活动中的最新记录
  1241. *
  1242. * @param int $activityId 活动ID
  1243. * @param int $userId 用户ID
  1244. * @param int $limit 限制数量
  1245. * @return array
  1246. */
  1247. public static function getUserLatestRecords($activityId, $userId, $limit = 10)
  1248. {
  1249. return LotteryUserChanceRecord::where('activity_id', $activityId)
  1250. ->where('user_id', $userId)
  1251. ->with(['condition', 'order', 'admin'])
  1252. ->order('get_time desc')
  1253. ->limit($limit)
  1254. ->select();
  1255. }
  1256. /**
  1257. * 获取活动中某种获取类型的记录统计
  1258. *
  1259. * @param int $activityId 活动ID
  1260. * @param int $getType 获取类型
  1261. * @return array
  1262. */
  1263. public static function getActivityRecordsByType($activityId, $getType)
  1264. {
  1265. $records = LotteryUserChanceRecord::where('activity_id', $activityId)
  1266. ->where('get_type', $getType)
  1267. ->select();
  1268. $stats = [
  1269. 'total_records' => count($records),
  1270. 'total_chances' => 0,
  1271. 'users' => [],
  1272. ];
  1273. foreach ($records as $record) {
  1274. $stats['total_chances'] += $record->chances;
  1275. if (!isset($stats['users'][$record->user_id])) {
  1276. $stats['users'][$record->user_id] = [
  1277. 'user_id' => $record->user_id,
  1278. 'records' => 0,
  1279. 'chances' => 0,
  1280. ];
  1281. }
  1282. $stats['users'][$record->user_id]['records']++;
  1283. $stats['users'][$record->user_id]['chances'] += $record->chances;
  1284. }
  1285. return $stats;
  1286. }
  1287. }