SuperballActivityService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. <?php
  2. namespace App\Services;
  3. use App\Facade\TableName;
  4. use App\Game\Services\OuroGameService;
  5. use App\Http\helper\NumConfig;
  6. use Carbon\Carbon;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Redis;
  9. /**
  10. * Superball Activity: recharge + turnover task, balls, lucky number, prize pool.
  11. * All amounts in internal units (NUM_VALUE) where needed for DB/score.
  12. */
  13. class SuperballActivityService
  14. {
  15. public const TIER_MAX = 'A';
  16. public const MULTIPLIER_MIN = 1.0;
  17. public const MULTIPLIER_MAX = 3.0;
  18. public const MULTIPLIER_STEP = 0.5;
  19. public const LUCKY_REWARD_PER_BALL = 10; // display unit per matching ball
  20. /**
  21. * Get full activity info: yesterday data, today data, tiers, user task, multiplier.
  22. */
  23. public function getInfo(int $userId): array
  24. {
  25. $today = Carbon::today()->format('Y-m-d');
  26. $yesterday = Carbon::yesterday()->format('Y-m-d');
  27. $tiers = $this->getTierConfig();
  28. $yesterdayDaily = $this->getOrCreateDaily($yesterday);
  29. $todayDaily = $this->getOrCreateDaily($today);
  30. $userTask = $this->getUserTask($userId, $today);
  31. $multiplierRow = $this->getUserMultiplier($userId);
  32. $rechargeToday = $this->getUserRechargeForDate($userId, $today);
  33. $turnoverToday = $this->getUserTotalBetForDate($userId, $today);
  34. $turnoverProgress = (int) $turnoverToday;
  35. $tierConfig = $userTask ? $this->getTierConfigByTier($userTask->tier) : null;
  36. $rechargeRequired = $tierConfig ? (int) $tierConfig->recharge_required : 0;
  37. $turnoverRequired = $tierConfig ? (int) $tierConfig->turnover_required : 0;
  38. $rechargeDisplay = $rechargeToday;
  39. $turnoverDisplay = $turnoverProgress / NumConfig::NUM_VALUE;
  40. $taskCompleted = $tierConfig && $rechargeDisplay >= $rechargeRequired && $turnoverDisplay >= $turnoverRequired;
  41. $canUpgrade = $userTask && $userTask->tier !== self::TIER_MAX && $taskCompleted;
  42. $canClaim = $taskCompleted && $userTask && (int) $userTask->status === 0;
  43. $yesterdayBalls = $this->getUserBalls($userId, $yesterday);
  44. $yesterdayLucky = (int) ($yesterdayDaily->lucky_number ?? 0);
  45. $yesterdayPrizeLog = $this->getUserPrizeLog($userId, $yesterday);
  46. $yesterdayBasePerBall = 0;
  47. if ($yesterdayDaily->total_balls > 0 && $yesterdayDaily->pool_amount > 0) {
  48. $yesterdayBasePerBall = (int) ($yesterdayDaily->pool_amount / $yesterdayDaily->total_balls);
  49. }
  50. $yesterdayMyPrize = $yesterdayPrizeLog ? (int) $yesterdayPrizeLog->total_amount : 0;
  51. $yesterdayMultiplier = $yesterdayPrizeLog ? (float) $yesterdayPrizeLog->multiplier : 1.0;
  52. $canClaimYesterday = false;
  53. $yesterdayPendingPrize = 0;
  54. if (!$yesterdayPrizeLog && count($yesterdayBalls) > 0) {
  55. $canClaimYesterday = true;
  56. $yesterdayPendingPrize = $this->calculateYesterdayPrizeForUser($userId, $yesterday);
  57. }
  58. $todayBasePerBall = 0;
  59. if ($todayDaily->total_balls > 0 && $todayDaily->pool_amount > 0) {
  60. $todayBasePerBall = (int) ($todayDaily->pool_amount / $todayDaily->total_balls);
  61. }
  62. $todayBalls = $this->getUserBalls($userId, $today);
  63. $todayMyBallsList = array_map(function ($b) {
  64. return ['ball_index' => (int) $b->ball_index, 'number' => (int) $b->number];
  65. }, $todayBalls);
  66. $todayNumberCounts = [];
  67. foreach ($todayBalls as $b) {
  68. $n = (int) $b->number;
  69. $todayNumberCounts[$n] = ($todayNumberCounts[$n] ?? 0) + 1;
  70. }
  71. // 0 点到 1 点前,前端展示的今日整体数据全部置为 0(不影响实际统计与任务进度)
  72. $hour = (int) Carbon::now()->format('G'); // 0-23
  73. if ($hour < 1) {
  74. $todayDisplayPoolAmount = 0;
  75. $todayDisplayCompleted = 0;
  76. $todayDisplayTotalBalls = 0;
  77. $todayDisplayBasePerBall = 0;
  78. $todayDisplayMyBalls = [];
  79. $todayDisplayNumberCounts = [];
  80. } else {
  81. $todayDisplayPoolAmount = (int) $todayDaily->pool_amount;
  82. $todayDisplayCompleted = (int) ($todayDaily->completed_count ?? 0);
  83. $todayDisplayTotalBalls = (int) ($todayDaily->total_balls ?? 0);
  84. $todayDisplayBasePerBall = $todayBasePerBall;
  85. $todayDisplayMyBalls = $todayMyBallsList;
  86. $todayDisplayNumberCounts = $todayNumberCounts;
  87. }
  88. $last7Lucky = $this->getLast7DaysLuckyNumbersPrivate();
  89. return [
  90. 'yesterday' => [
  91. 'pool_amount' => (int) $yesterdayDaily->pool_amount,
  92. 'pool_amount_display' => (int) $yesterdayDaily->pool_amount / NumConfig::NUM_VALUE,
  93. 'base_reward_per_ball' => $yesterdayBasePerBall,
  94. 'base_reward_per_ball_display' => $yesterdayBasePerBall / NumConfig::NUM_VALUE,
  95. 'lucky_number' => $yesterdayLucky,
  96. 'completed_count' => (int) ($yesterdayDaily->completed_count ?? 0),
  97. 'total_balls' => (int) ($yesterdayDaily->total_balls ?? 0),
  98. 'my_balls' => $yesterdayBalls,
  99. 'my_balls_with_lucky' => array_map(function ($b) use ($yesterdayLucky) {
  100. return ['number' => (int) $b->number, 'is_lucky' => (int) $b->number === $yesterdayLucky];
  101. }, $yesterdayBalls),
  102. 'my_prize' => $yesterdayMyPrize,
  103. 'my_prize_display' => $yesterdayMyPrize / NumConfig::NUM_VALUE,
  104. 'my_multiplier' => $yesterdayMultiplier,
  105. 'can_claim_yesterday' => $canClaimYesterday,
  106. 'pending_prize' => $yesterdayPendingPrize,
  107. 'pending_prize_display' => $yesterdayPendingPrize / NumConfig::NUM_VALUE,
  108. ],
  109. 'today' => [
  110. 'pool_amount' => $todayDisplayPoolAmount,
  111. 'pool_amount_display' => $todayDisplayPoolAmount / NumConfig::NUM_VALUE,
  112. 'completed_count' => $todayDisplayCompleted,
  113. 'total_balls' => $todayDisplayTotalBalls,
  114. 'base_reward_per_ball' => $todayDisplayBasePerBall,
  115. 'base_reward_per_ball_display' => $todayDisplayBasePerBall / NumConfig::NUM_VALUE,
  116. 'my_balls' => $todayDisplayMyBalls,
  117. 'number_counts' => $todayDisplayNumberCounts,
  118. ],
  119. 'tiers' => $tiers,
  120. 'user_task' => $userTask ? [
  121. 'tier' => $userTask->tier,
  122. 'recharge_required' => $rechargeRequired,
  123. 'turnover_required' => $turnoverRequired,
  124. 'recharge_progress' => $rechargeDisplay,
  125. 'turnover_progress' => $turnoverDisplay,
  126. 'task_completed' => $taskCompleted,
  127. 'status' => (int) $userTask->status,
  128. 'can_claim' => $canClaim,
  129. 'can_upgrade' => $canUpgrade,
  130. 'ball_count' => $tierConfig ? (int) $tierConfig->ball_count : 0,
  131. ] : null,
  132. 'multiplier' => [
  133. 'value' => (float) ($multiplierRow->multiplier ?? 1.0),
  134. 'consecutive_days' => (int) ($multiplierRow->consecutive_days ?? 0),
  135. 'min' => self::MULTIPLIER_MIN,
  136. 'max' => self::MULTIPLIER_MAX,
  137. 'step' => self::MULTIPLIER_STEP,
  138. ],
  139. 'lucky_reward_per_ball' => self::LUCKY_REWARD_PER_BALL,
  140. 'lucky_numbers_7_days' => $last7Lucky,
  141. ];
  142. }
  143. /**
  144. * Select task tier for today (with optional confirm). Creates or updates user task.
  145. * @return array success: ['success' => true] | failure: ['success' => false, 'message' => ['key', 'fallback']]
  146. */
  147. public function selectTier(int $userId, string $tier): array
  148. {
  149. $today = Carbon::today()->format('Y-m-d');
  150. $config = $this->getTierConfigByTier($tier);
  151. if (!$config) {
  152. return ['success' => false, 'message' => ['web.superball.activity_not_found', 'Activity not found']];
  153. }
  154. $existing = $this->getUserTask($userId, $today);
  155. if ($existing) {
  156. return ['success' => false, 'message' => ['web.superball.tier_already_selected', 'Already selected tier for today']];
  157. }
  158. DB::connection('write')->table(TableName::agent() . 'superball_user_task')->insert([
  159. 'user_id' => $userId,
  160. 'task_date' => $today,
  161. 'tier' => $tier,
  162. 'total_bet_snapshot' => 0,
  163. 'status' => 0,
  164. 'created_at' => now()->format('Y-m-d H:i:s'),
  165. 'updated_at' => now()->format('Y-m-d H:i:s'),
  166. ]);
  167. return ['success' => true];
  168. }
  169. /**
  170. * Upgrade to higher tier (keep progress). Only allowed when task completed and not A.
  171. * @return array success: ['success' => true] | failure: ['success' => false, 'message' => [...]]
  172. */
  173. public function upgradeTier(int $userId, string $newTier): array
  174. {
  175. $today = Carbon::today()->format('Y-m-d');
  176. $task = $this->getUserTask($userId, $today);
  177. if (!$task) {
  178. return ['success' => false, 'message' => ['web.superball.no_task_today', 'No task for today']];
  179. }
  180. if ((int) $task->status === 1) {
  181. return ['success' => false, 'message' => ['web.superball.already_claimed', 'Already claimed']];
  182. }
  183. $tierOrder = ['E' => 1, 'D' => 2, 'C' => 3, 'B' => 4, 'A' => 5];
  184. $currentOrder = $tierOrder[$task->tier] ?? 0;
  185. $newOrder = $tierOrder[$newTier] ?? 0;
  186. if ($newOrder <= $currentOrder) {
  187. return ['success' => false, 'message' => ['web.superball.cannot_downgrade', 'Can only upgrade to higher tier']];
  188. }
  189. $rechargeToday = $this->getUserRechargeForDate($userId, $today);
  190. $turnoverToday = $this->getUserTotalBetForDate($userId, $today);
  191. $newConfig = $this->getTierConfigByTier($task->tier);
  192. $rechargeOk = $rechargeToday >= (int) $newConfig->recharge_required;
  193. $turnoverOk = ($turnoverToday / NumConfig::NUM_VALUE) >= (int) $newConfig->turnover_required;
  194. // var_dump($rechargeToday,$turnoverToday,$newConfig);
  195. if (!$rechargeOk || !$turnoverOk) {
  196. return ['success' => false, 'message' => ['web.superball.task_not_completed', 'Task not completed']];
  197. }
  198. DB::connection('write')->table(TableName::agent() . 'superball_user_task')
  199. ->where('user_id', $userId)
  200. ->where('task_date', $today)
  201. ->update(['tier' => $newTier, 'updated_at' => now()->format('Y-m-d H:i:s')]);
  202. return ['success' => true,'user_id' => $userId, 'new_tier' => $newTier,'task_date'=>$today];
  203. }
  204. /**
  205. * Claim reward: grant balls, update daily total_balls/completed_count, update multiplier, mark task claimed.
  206. * @return array success: ['ball_count' => n, 'message' => ...] | failure: ['success' => false, 'message' => [...]]
  207. */
  208. public function claimReward(int $userId): array
  209. {
  210. $today = Carbon::today()->format('Y-m-d');
  211. $task = $this->getUserTask($userId, $today);
  212. if (!$task) {
  213. return ['success' => false, 'message' => ['web.superball.no_task_today', 'No task for today']];
  214. }
  215. if ((int) $task->status === 1) {
  216. return ['success' => false, 'message' => ['web.superball.already_claimed', 'Already claimed']];
  217. }
  218. $tierConfig = $this->getTierConfigByTier($task->tier);
  219. if (!$tierConfig) {
  220. return ['success' => false, 'message' => ['web.superball.activity_not_found', 'Activity not found']];
  221. }
  222. $rechargeToday = $this->getUserRechargeForDate($userId, $today);
  223. $turnoverToday = $this->getUserTotalBetForDate($userId, $today);
  224. $rechargeOk = ($rechargeToday) >= (int) $tierConfig->recharge_required;
  225. $turnoverOk = ($turnoverToday / NumConfig::NUM_VALUE) >= (int) $tierConfig->turnover_required;
  226. if (!$rechargeOk || !$turnoverOk) {
  227. return ['success' => false, 'message' => ['web.superball.task_not_completed', 'Task not completed']];
  228. }
  229. $ballCount = (int) $tierConfig->ball_count;
  230. DB::connection('write')->transaction(function () use ($userId, $today, $task, $ballCount) {
  231. DB::connection('write')->table(TableName::agent() . 'superball_user_task')
  232. ->where('user_id', $userId)
  233. ->where('task_date', $today)
  234. ->update(['status' => 1, 'updated_at' => now()->format('Y-m-d H:i:s')]);
  235. $daily = DB::connection('write')->table(TableName::agent() . 'superball_daily')
  236. ->where('pool_date', $today)
  237. ->lockForUpdate()
  238. ->first();
  239. if ($daily) {
  240. DB::connection('write')->table(TableName::agent() . 'superball_daily')
  241. ->where('pool_date', $today)
  242. ->update([
  243. 'total_balls' => (int) $daily->total_balls + $ballCount,
  244. 'completed_count' => (int) $daily->completed_count + 1,
  245. 'updated_at' => now()->format('Y-m-d H:i:s'),
  246. ]);
  247. }
  248. $this->updateUserMultiplier($userId, $today);
  249. });
  250. return [
  251. 'ball_count' => $ballCount,
  252. 'message' => 'Claim success, please select numbers for your balls',
  253. ];
  254. }
  255. /**
  256. * Submit numbers for all balls (0-9 per ball). Must have claimed and not yet submitted.
  257. * @return array success: ['success' => true] | failure: ['success' => false, 'message' => [...]]
  258. */
  259. public function submitNumbers(int $userId, array $numbers): array
  260. {
  261. $today = Carbon::today()->format('Y-m-d');
  262. $task = $this->getUserTask($userId, $today);
  263. if (!$task || (int) $task->status !== 1) {
  264. return ['success' => false, 'message' => ['web.superball.no_claimed_task', 'No claimed task for today']];
  265. }
  266. $tierConfig = $this->getTierConfigByTier($task->tier);
  267. if (!$tierConfig) {
  268. return ['success' => false, 'message' => ['web.superball.activity_not_found', 'Activity not found']];
  269. }
  270. $ballCount = (int) $tierConfig->ball_count;
  271. if (count($numbers) !== $ballCount) {
  272. return ['success' => false, 'message' => ['web.superball.number_count_mismatch', 'Number count mismatch']];
  273. }
  274. $existing = DB::connection('write')->table(TableName::agent() . 'superball_user_balls')
  275. ->where('user_id', $userId)
  276. ->where('ball_date', $today)
  277. ->count();
  278. if ($existing > 0) {
  279. return ['success' => false, 'message' => ['web.superball.numbers_already_submitted', 'Numbers already submitted']];
  280. }
  281. DB::connection('write')->transaction(function () use ($userId, $today, $numbers) {
  282. // 写入用户今日所有球号
  283. foreach ($numbers as $index => $num) {
  284. $n = (int) $num;
  285. if ($n < 0 || $n > 9) {
  286. throw new \RuntimeException('Number must be 0-9');
  287. }
  288. DB::connection('write')->table(TableName::agent() . 'superball_user_balls')->insert([
  289. 'user_id' => $userId,
  290. 'ball_date' => $today,
  291. 'ball_index' => $index + 1,
  292. 'number' => $n,
  293. 'created_at' => now()->format('Y-m-d H:i:s'),
  294. ]);
  295. }
  296. // 若用户选择的号码等于当日 lucky_number,则把 superball_daily.lucky_count 累加
  297. $daily = DB::connection('write')
  298. ->table(TableName::agent() . 'superball_daily')
  299. ->where('pool_date', $today)
  300. ->lockForUpdate()
  301. ->first();
  302. if ($daily) {
  303. $luckyNumber = (int) $daily->lucky_number;
  304. $matched = 0;
  305. foreach ($numbers as $num) {
  306. if ((int) $num === $luckyNumber) {
  307. $matched++;
  308. }
  309. }
  310. if ($matched > 0) {
  311. DB::connection('write')
  312. ->table(TableName::agent() . 'superball_daily')
  313. ->where('pool_date', $today)
  314. ->update([
  315. 'lucky_count' => (int) $daily->lucky_count + $matched,
  316. 'updated_at' => now()->format('Y-m-d H:i:s'),
  317. ]);
  318. }
  319. }
  320. });
  321. return ['success' => true];
  322. }
  323. /**
  324. * Get user's balls for a date (for number selection page or display).
  325. */
  326. public function getMyBalls(int $userId, string $date): array
  327. {
  328. $rows = DB::table(TableName::agent() . 'superball_user_balls')
  329. ->where('user_id', $userId)
  330. ->where('ball_date', $date)
  331. ->orderBy('ball_index')
  332. ->get();
  333. return array_map(function ($r) {
  334. return ['ball_index' => (int) $r->ball_index, 'number' => (int) $r->number];
  335. }, $rows->all());
  336. }
  337. /**
  338. * User claims yesterday's reward (next-day claim, no auto distribution).
  339. * Formula: base = pool / total_balls * ball_count, lucky = 10 * matched_balls (display), total = base * multiplier + lucky.
  340. * @return array success: data with total_amount etc. | failure: ['success' => false, 'message' => [...]]
  341. */
  342. public function claimYesterdayReward(int $userId): array
  343. {
  344. $yesterday = Carbon::yesterday()->format('Y-m-d');
  345. $existing = $this->getUserPrizeLog($userId, $yesterday);
  346. if ($existing) {
  347. return ['success' => false, 'message' => ['web.superball.yesterday_already_claimed', 'Yesterday reward already claimed']];
  348. }
  349. $balls = $this->getUserBalls($userId, $yesterday);
  350. if (count($balls) === 0) {
  351. return ['success' => false, 'message' => ['web.superball.no_balls_yesterday', 'No balls for yesterday, nothing to claim']];
  352. }
  353. $daily = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $yesterday)->first();
  354. if (!$daily || (int) $daily->total_balls <= 0) {
  355. return ['success' => false, 'message' => ['web.superball.pool_not_ready', 'Yesterday pool not ready']];
  356. }
  357. $basePerBall = (int) ($daily->pool_amount / $daily->total_balls);
  358. $luckyNumber = (int) $daily->lucky_number;
  359. $multiplierRow = $this->getUserMultiplier($userId);
  360. $multiplier = (float) ($multiplierRow->multiplier ?? 1.0);
  361. // 选号可重复:每个球单独比对幸运号,中奖球数 = 号码等于幸运号的球个数(同一号码可多球)
  362. $matched = 0;
  363. foreach ($balls as $b) {
  364. if ((int) $b->number === $luckyNumber) {
  365. $matched++;
  366. }
  367. }
  368. $baseAmount = $basePerBall * count($balls);
  369. $luckyAmountDisplay = self::LUCKY_REWARD_PER_BALL * $matched;
  370. $luckyAmountInternal = $luckyAmountDisplay * NumConfig::NUM_VALUE;
  371. $totalAmount = (int) round($baseAmount * $multiplier) + $luckyAmountInternal;
  372. DB::connection('write')->table(TableName::agent() . 'superball_prize_log')->insert([
  373. 'user_id' => $userId,
  374. 'settle_date' => $yesterday,
  375. 'base_amount' => $baseAmount,
  376. 'lucky_amount' => $luckyAmountInternal,
  377. 'multiplier' => $multiplier,
  378. 'total_amount' => $totalAmount,
  379. 'created_at' => now()->format('Y-m-d H:i:s'),
  380. ]);
  381. OuroGameService::AddScore($userId, $totalAmount, 90);
  382. return [
  383. 'total_amount' => $totalAmount,
  384. 'total_amount_display' => $totalAmount / NumConfig::NUM_VALUE,
  385. 'base_amount' => $baseAmount,
  386. 'lucky_amount' => $luckyAmountInternal,
  387. 'multiplier' => $multiplier,
  388. ];
  389. }
  390. /**
  391. * Calculate yesterday prize for user (for display only, no claim).
  392. */
  393. public function calculateYesterdayPrizeForUser(int $userId, string $yesterday): int
  394. {
  395. $daily = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $yesterday)->first();
  396. if (!$daily || (int) $daily->total_balls <= 0) {
  397. return 0;
  398. }
  399. $balls = $this->getUserBalls($userId, $yesterday);
  400. if (count($balls) === 0) {
  401. return 0;
  402. }
  403. $basePerBall = (int) ($daily->pool_amount / $daily->total_balls);
  404. $luckyNumber = (int) $daily->lucky_number;
  405. $multiplierRow = $this->getUserMultiplier($userId);
  406. $multiplier = (float) ($multiplierRow->multiplier ?? 1.0);
  407. // 选号可重复:按球逐个比对幸运号,中奖球数 = 号码等于幸运号的球个数
  408. $matched = 0;
  409. foreach ($balls as $b) {
  410. if ((int) $b->number === $luckyNumber) {
  411. $matched++;
  412. }
  413. }
  414. $baseAmount = $basePerBall * count($balls);
  415. $luckyAmountInternal = self::LUCKY_REWARD_PER_BALL * $matched * NumConfig::NUM_VALUE;
  416. return (int) round($baseAmount * $multiplier) + $luckyAmountInternal;
  417. }
  418. /**
  419. * Get last 7 days lucky numbers (for display).
  420. */
  421. public function getLast7DaysLuckyNumbers(): array
  422. {
  423. return $this->getLast7DaysLuckyNumbersPrivate();
  424. }
  425. /**
  426. * Ensure daily row and lucky number for date (idempotent).
  427. */
  428. public function getOrCreateDaily(string $date): \stdClass
  429. {
  430. $row = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $date)->first();
  431. if ($row) {
  432. return $row;
  433. }
  434. $lucky = mt_rand(0, 9);
  435. DB::connection('write')->table(TableName::agent() . 'superball_daily')->insert([
  436. 'pool_date' => $date,
  437. 'pool_amount' => 0,
  438. 'total_balls' => 0,
  439. 'lucky_number' => $lucky,
  440. 'completed_count' => 0,
  441. 'lucky_count' => 0,
  442. 'created_at' => now()->format('Y-m-d H:i:s'),
  443. 'updated_at' => now()->format('Y-m-d H:i:s'),
  444. ]);
  445. return DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $date)->first();
  446. }
  447. /**
  448. * Update pool amount for a date (call from job that aggregates daily turnover).
  449. */
  450. public function updatePoolAmount(string $date, int $poolAmountInternal): void
  451. {
  452. DB::connection('write')->table(TableName::agent() . 'superball_daily')
  453. ->where('pool_date', $date)
  454. ->update(['pool_amount' => $poolAmountInternal, 'updated_at' => now()->format('Y-m-d H:i:s')]);
  455. }
  456. // --- private helpers ---
  457. private function getTierConfig(): array
  458. {
  459. $rows = DB::table(TableName::agent() . 'superball_tier_config')
  460. ->orderBy('sort_index')
  461. ->get();
  462. return array_map(function ($r) {
  463. return [
  464. 'tier' => $r->tier,
  465. 'recharge_required' => (int) $r->recharge_required,
  466. 'turnover_required' => (int) $r->turnover_required,
  467. 'ball_count' => (int) $r->ball_count,
  468. ];
  469. }, $rows->all());
  470. }
  471. private function getTierConfigByTier(string $tier): ?\stdClass
  472. {
  473. return DB::table(TableName::agent() . 'superball_tier_config')->where('tier', $tier)->first();
  474. }
  475. private function getUserTask(int $userId, string $date): ?\stdClass
  476. {
  477. return DB::table(TableName::agent() . 'superball_user_task')
  478. ->where('user_id', $userId)
  479. ->where('task_date', $date)
  480. ->first();
  481. }
  482. private function getUserRechargeForDate(int $userId, string $date): int
  483. {
  484. $dateId = str_replace('-', '', $date);
  485. $row = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew')
  486. ->where('UserID', $userId)
  487. ->where('DateID', $dateId)
  488. ->first();
  489. return $row ? (int) $row->Recharge : 0;
  490. }
  491. /** 当日流水:从按日统计表取当天 TotalBet(内部单位) */
  492. private function getUserTotalBetForDate(int $userId, string $date): int
  493. {
  494. $dateId = str_replace('-', '', $date);
  495. $row = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew')
  496. ->where('UserID', $userId)
  497. ->where('DateID', $dateId)
  498. ->first();
  499. return $row && isset($row->TotalBet) ? (int) $row->TotalBet : 0;
  500. }
  501. private function getUserTotalBet(int $userId): int
  502. {
  503. $row = DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')
  504. ->where('UserID', $userId)
  505. ->first();
  506. return $row ? (int) $row->TotalBet : 0;
  507. }
  508. private function getUserBalls(int $userId, string $date): array
  509. {
  510. return DB::table(TableName::agent() . 'superball_user_balls')
  511. ->where('user_id', $userId)
  512. ->where('ball_date', $date)
  513. ->orderBy('ball_index')
  514. ->get()
  515. ->all();
  516. }
  517. private function getUserMultiplier(int $userId): ?\stdClass
  518. {
  519. return DB::table(TableName::agent() . 'superball_user_multiplier')->where('user_id', $userId)->first();
  520. }
  521. private function getUserPrizeLog(int $userId, string $date): ?\stdClass
  522. {
  523. return DB::table(TableName::agent() . 'superball_prize_log')
  524. ->where('user_id', $userId)
  525. ->where('settle_date', $date)
  526. ->first();
  527. }
  528. private function getLast7DaysLuckyNumbersPrivate(): array
  529. {
  530. $dates = [];
  531. for ($i = 0; $i < 7; $i++) {
  532. $dates[] = Carbon::today()->subDays($i)->format('Y-m-d');
  533. }
  534. $rows = DB::table(TableName::agent() . 'superball_daily')
  535. ->whereIn('pool_date', $dates)
  536. ->orderBy('pool_date', 'desc')
  537. ->get();
  538. $map = [];
  539. foreach ($rows as $r) {
  540. $map[$r->pool_date] = (int) $r->lucky_number;
  541. }
  542. return array_map(function ($d) use ($map) {
  543. return ['date' => $d, 'lucky_number' => $map[$d] ?? null];
  544. }, $dates);
  545. }
  546. private function updateUserMultiplier(int $userId, string $taskDate): void
  547. {
  548. $row = DB::connection('write')->table(TableName::agent() . 'superball_user_multiplier')
  549. ->where('user_id', $userId)
  550. ->lockForUpdate()
  551. ->first();
  552. $multiplier = self::MULTIPLIER_MIN;
  553. $consecutive = 1;
  554. if ($row) {
  555. $last = $row->last_task_date ? (string) $row->last_task_date : null;
  556. $prev = Carbon::parse($taskDate)->subDay()->format('Y-m-d');
  557. if ($last === $prev) {
  558. $consecutive = (int) $row->consecutive_days + 1;
  559. $multiplier = min(self::MULTIPLIER_MAX, (float) $row->multiplier + self::MULTIPLIER_STEP);
  560. } elseif ($last !== null && $last !== $taskDate) {
  561. $daysDiff = (int) Carbon::parse($taskDate)->diffInDays(Carbon::parse($last));
  562. if ($daysDiff > 1) {
  563. $multiplier = max(self::MULTIPLIER_MIN, (float) $row->multiplier - self::MULTIPLIER_STEP);
  564. $consecutive = 1;
  565. } else {
  566. $multiplier = (float) $row->multiplier;
  567. $consecutive = (int) $row->consecutive_days + 1;
  568. }
  569. }
  570. }
  571. DB::connection('write')->table(TableName::agent() . 'superball_user_multiplier')->updateOrInsert(
  572. ['user_id' => $userId],
  573. [
  574. 'consecutive_days' => $consecutive,
  575. 'last_task_date' => $taskDate,
  576. 'multiplier' => $multiplier,
  577. 'updated_at' => now()->format('Y-m-d H:i:s'),
  578. ]
  579. );
  580. }
  581. }