2
0

SuperballActivityService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. // Perform atomic increments in a single query to avoid holding an explicit row lock via SELECT ... FOR UPDATE.
  236. // This is safe because we only increment if the record already exists (same behavior as before).
  237. DB::connection('write')->table(TableName::agent() . 'superball_daily')
  238. ->where('pool_date', $today)
  239. ->update([
  240. 'total_balls' => DB::raw("total_balls + {$ballCount}"),
  241. 'completed_count' => DB::raw('completed_count + 1'),
  242. 'updated_at' => now()->format('Y-m-d H:i:s'),
  243. ]);
  244. $this->updateUserMultiplier($userId, $today);
  245. });
  246. return [
  247. 'ball_count' => $ballCount,
  248. 'message' => 'Claim success, please select numbers for your balls',
  249. ];
  250. }
  251. /**
  252. * Submit numbers for all balls (0-9 per ball). Must have claimed and not yet submitted.
  253. * @return array success: ['success' => true] | failure: ['success' => false, 'message' => [...]]
  254. */
  255. public function submitNumbers(int $userId, array $numbers): array
  256. {
  257. $today = Carbon::today()->format('Y-m-d');
  258. $task = $this->getUserTask($userId, $today);
  259. if (!$task || (int) $task->status !== 1) {
  260. return ['success' => false, 'message' => ['web.superball.no_claimed_task', 'No claimed task for today']];
  261. }
  262. $tierConfig = $this->getTierConfigByTier($task->tier);
  263. if (!$tierConfig) {
  264. return ['success' => false, 'message' => ['web.superball.activity_not_found', 'Activity not found']];
  265. }
  266. $ballCount = (int) $tierConfig->ball_count;
  267. if (count($numbers) !== $ballCount) {
  268. return ['success' => false, 'message' => ['web.superball.number_count_mismatch', 'Number count mismatch']];
  269. }
  270. $existing = DB::connection('write')->table(TableName::agent() . 'superball_user_balls')
  271. ->where('user_id', $userId)
  272. ->where('ball_date', $today)
  273. ->count();
  274. if ($existing > 0) {
  275. return ['success' => false, 'message' => ['web.superball.numbers_already_submitted', 'Numbers already submitted']];
  276. }
  277. DB::connection('write')->transaction(function () use ($userId, $today, $numbers) {
  278. // 写入用户今日所有球号
  279. foreach ($numbers as $index => $num) {
  280. $n = (int) $num;
  281. if ($n < 0 || $n > 9) {
  282. throw new \RuntimeException('Number must be 0-9');
  283. }
  284. DB::connection('write')->table(TableName::agent() . 'superball_user_balls')->insert([
  285. 'user_id' => $userId,
  286. 'ball_date' => $today,
  287. 'ball_index' => $index + 1,
  288. 'number' => $n,
  289. 'created_at' => now()->format('Y-m-d H:i:s'),
  290. ]);
  291. }
  292. // 若用户选择的号码等于当日 lucky_number,则把 superball_daily.lucky_count 累加(使用原子自增,避免锁住整行)
  293. $daily = DB::connection('write')
  294. ->table(TableName::agent() . 'superball_daily')
  295. ->lock('with(nolock)')
  296. ->where('pool_date', $today)
  297. ->first();
  298. if ($daily) {
  299. $luckyNumber = (int) $daily->lucky_number;
  300. $matched = 0;
  301. foreach ($numbers as $num) {
  302. if ((int) $num === $luckyNumber) {
  303. $matched++;
  304. }
  305. }
  306. if ($matched > 0) {
  307. DB::connection('write')
  308. ->table(TableName::agent() . 'superball_daily')
  309. ->where('pool_date', $today)
  310. ->update([
  311. 'lucky_count' => DB::raw("lucky_count + {$matched}"),
  312. 'updated_at' => now()->format('Y-m-d H:i:s'),
  313. ]);
  314. }
  315. }
  316. });
  317. return ['success' => true];
  318. }
  319. /**
  320. * Get user's balls for a date (for number selection page or display).
  321. */
  322. public function getMyBalls(int $userId, string $date): array
  323. {
  324. $rows = DB::table(TableName::agent() . 'superball_user_balls')
  325. ->where('user_id', $userId)
  326. ->where('ball_date', $date)
  327. ->orderBy('ball_index')
  328. ->get();
  329. return array_map(function ($r) {
  330. return ['ball_index' => (int) $r->ball_index, 'number' => (int) $r->number];
  331. }, $rows->all());
  332. }
  333. /**
  334. * User claims yesterday's reward (next-day claim, no auto distribution).
  335. * Formula: base = pool / total_balls * ball_count, lucky = 10 * matched_balls (display), total = base * multiplier + lucky.
  336. * @return array success: data with total_amount etc. | failure: ['success' => false, 'message' => [...]]
  337. */
  338. public function claimYesterdayReward(int $userId): array
  339. {
  340. $yesterday = Carbon::yesterday()->format('Y-m-d');
  341. $existing = $this->getUserPrizeLog($userId, $yesterday);
  342. if ($existing) {
  343. return ['success' => false, 'message' => ['web.superball.yesterday_already_claimed', 'Yesterday reward already claimed']];
  344. }
  345. $balls = $this->getUserBalls($userId, $yesterday);
  346. if (count($balls) === 0) {
  347. return ['success' => false, 'message' => ['web.superball.no_balls_yesterday', 'No balls for yesterday, nothing to claim']];
  348. }
  349. $daily = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $yesterday)->first();
  350. if (!$daily || (int) $daily->total_balls <= 0) {
  351. return ['success' => false, 'message' => ['web.superball.pool_not_ready', 'Yesterday pool not ready']];
  352. }
  353. $basePerBall = (int) ($daily->pool_amount / $daily->total_balls);
  354. $luckyNumber = (int) $daily->lucky_number;
  355. $multiplierRow = $this->getUserMultiplier($userId);
  356. $multiplier = (float) ($multiplierRow->multiplier ?? 1.0);
  357. // 选号可重复:每个球单独比对幸运号,中奖球数 = 号码等于幸运号的球个数(同一号码可多球)
  358. $matched = 0;
  359. foreach ($balls as $b) {
  360. if ((int) $b->number === $luckyNumber) {
  361. $matched++;
  362. }
  363. }
  364. $baseAmount = $basePerBall * count($balls);
  365. $luckyAmountDisplay = self::LUCKY_REWARD_PER_BALL * $matched;
  366. $luckyAmountInternal = $luckyAmountDisplay * NumConfig::NUM_VALUE;
  367. $totalAmount = (int) round($baseAmount * $multiplier) + $luckyAmountInternal;
  368. DB::connection('write')->table(TableName::agent() . 'superball_prize_log')->insert([
  369. 'user_id' => $userId,
  370. 'settle_date' => $yesterday,
  371. 'base_amount' => $baseAmount,
  372. 'lucky_amount' => $luckyAmountInternal,
  373. 'multiplier' => $multiplier,
  374. 'total_amount' => $totalAmount,
  375. 'created_at' => now()->format('Y-m-d H:i:s'),
  376. ]);
  377. OuroGameService::AddScore($userId, $totalAmount, 90);
  378. return [
  379. 'total_amount' => $totalAmount,
  380. 'total_amount_display' => $totalAmount / NumConfig::NUM_VALUE,
  381. 'base_amount' => $baseAmount,
  382. 'lucky_amount' => $luckyAmountInternal,
  383. 'multiplier' => $multiplier,
  384. ];
  385. }
  386. /**
  387. * Calculate yesterday prize for user (for display only, no claim).
  388. */
  389. public function calculateYesterdayPrizeForUser(int $userId, string $yesterday): int
  390. {
  391. $daily = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $yesterday)->first();
  392. if (!$daily || (int) $daily->total_balls <= 0) {
  393. return 0;
  394. }
  395. $balls = $this->getUserBalls($userId, $yesterday);
  396. if (count($balls) === 0) {
  397. return 0;
  398. }
  399. $basePerBall = (int) ($daily->pool_amount / $daily->total_balls);
  400. $luckyNumber = (int) $daily->lucky_number;
  401. $multiplierRow = $this->getUserMultiplier($userId);
  402. $multiplier = (float) ($multiplierRow->multiplier ?? 1.0);
  403. // 选号可重复:按球逐个比对幸运号,中奖球数 = 号码等于幸运号的球个数
  404. $matched = 0;
  405. foreach ($balls as $b) {
  406. if ((int) $b->number === $luckyNumber) {
  407. $matched++;
  408. }
  409. }
  410. $baseAmount = $basePerBall * count($balls);
  411. $luckyAmountInternal = self::LUCKY_REWARD_PER_BALL * $matched * NumConfig::NUM_VALUE;
  412. return (int) round($baseAmount * $multiplier) + $luckyAmountInternal;
  413. }
  414. /**
  415. * Get last 7 days lucky numbers (for display).
  416. */
  417. public function getLast7DaysLuckyNumbers(): array
  418. {
  419. return $this->getLast7DaysLuckyNumbersPrivate();
  420. }
  421. /**
  422. * Ensure daily row and lucky number for date (idempotent).
  423. */
  424. public function getOrCreateDaily(string $date): \stdClass
  425. {
  426. $row = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $date)->first();
  427. if ($row) {
  428. return $row;
  429. }
  430. $lucky = mt_rand(0, 9);
  431. DB::connection('write')->table(TableName::agent() . 'superball_daily')->insert([
  432. 'pool_date' => $date,
  433. 'pool_amount' => 0,
  434. 'total_balls' => 0,
  435. 'lucky_number' => $lucky,
  436. 'completed_count' => 0,
  437. 'lucky_count' => 0,
  438. 'created_at' => now()->format('Y-m-d H:i:s'),
  439. 'updated_at' => now()->format('Y-m-d H:i:s'),
  440. ]);
  441. return DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $date)->first();
  442. }
  443. /**
  444. * Update pool amount for a date (call from job that aggregates daily turnover).
  445. */
  446. public function updatePoolAmount(string $date, int $poolAmountInternal): void
  447. {
  448. DB::connection('write')->table(TableName::agent() . 'superball_daily')
  449. ->where('pool_date', $date)
  450. ->update(['pool_amount' => $poolAmountInternal, 'updated_at' => now()->format('Y-m-d H:i:s')]);
  451. }
  452. // --- private helpers ---
  453. private function getTierConfig(): array
  454. {
  455. $rows = DB::table(TableName::agent() . 'superball_tier_config')
  456. ->orderBy('sort_index')
  457. ->get();
  458. return array_map(function ($r) {
  459. return [
  460. 'tier' => $r->tier,
  461. 'recharge_required' => (int) $r->recharge_required,
  462. 'turnover_required' => (int) $r->turnover_required,
  463. 'ball_count' => (int) $r->ball_count,
  464. ];
  465. }, $rows->all());
  466. }
  467. private function getTierConfigByTier(string $tier): ?\stdClass
  468. {
  469. return DB::table(TableName::agent() . 'superball_tier_config')->where('tier', $tier)->first();
  470. }
  471. private function getUserTask(int $userId, string $date): ?\stdClass
  472. {
  473. return DB::table(TableName::agent() . 'superball_user_task')
  474. ->where('user_id', $userId)
  475. ->where('task_date', $date)
  476. ->first();
  477. }
  478. private function getUserRechargeForDate(int $userId, string $date): int
  479. {
  480. $dateId = str_replace('-', '', $date);
  481. $row = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew')
  482. ->where('UserID', $userId)
  483. ->where('DateID', $dateId)
  484. ->first();
  485. return $row ? (int) $row->Recharge : 0;
  486. }
  487. /** 当日流水:从按日统计表取当天 TotalBet(内部单位) */
  488. private function getUserTotalBetForDate(int $userId, string $date): int
  489. {
  490. $dateId = str_replace('-', '', $date);
  491. $row = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew')
  492. ->where('UserID', $userId)
  493. ->where('DateID', $dateId)
  494. ->first();
  495. return $row && isset($row->TotalBet) ? (int) $row->TotalBet : 0;
  496. }
  497. private function getUserTotalBet(int $userId): int
  498. {
  499. $row = DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')
  500. ->where('UserID', $userId)
  501. ->first();
  502. return $row ? (int) $row->TotalBet : 0;
  503. }
  504. private function getUserBalls(int $userId, string $date): array
  505. {
  506. return DB::table(TableName::agent() . 'superball_user_balls')
  507. ->where('user_id', $userId)
  508. ->where('ball_date', $date)
  509. ->orderBy('ball_index')
  510. ->get()
  511. ->all();
  512. }
  513. private function getUserMultiplier(int $userId): ?\stdClass
  514. {
  515. return DB::table(TableName::agent() . 'superball_user_multiplier')->where('user_id', $userId)->first();
  516. }
  517. private function getUserPrizeLog(int $userId, string $date): ?\stdClass
  518. {
  519. return DB::table(TableName::agent() . 'superball_prize_log')
  520. ->where('user_id', $userId)
  521. ->where('settle_date', $date)
  522. ->first();
  523. }
  524. private function getLast7DaysLuckyNumbersPrivate(): array
  525. {
  526. $dates = [];
  527. for ($i = 0; $i < 7; $i++) {
  528. $dates[] = Carbon::today()->subDays($i)->format('Y-m-d');
  529. }
  530. $rows = DB::table(TableName::agent() . 'superball_daily')
  531. ->whereIn('pool_date', $dates)
  532. ->orderBy('pool_date', 'desc')
  533. ->get();
  534. $map = [];
  535. foreach ($rows as $r) {
  536. $map[$r->pool_date] = (int) $r->lucky_number;
  537. }
  538. return array_map(function ($d) use ($map) {
  539. return ['date' => $d, 'lucky_number' => $map[$d] ?? null];
  540. }, $dates);
  541. }
  542. private function updateUserMultiplier(int $userId, string $taskDate): void
  543. {
  544. $row = DB::connection('write')->table(TableName::agent() . 'superball_user_multiplier')
  545. ->where('user_id', $userId)
  546. ->lockForUpdate()
  547. ->first();
  548. $multiplier = self::MULTIPLIER_MIN;
  549. $consecutive = 1;
  550. if ($row) {
  551. $last = $row->last_task_date ? (string) $row->last_task_date : null;
  552. $prev = Carbon::parse($taskDate)->subDay()->format('Y-m-d');
  553. if ($last === $prev) {
  554. $consecutive = (int) $row->consecutive_days + 1;
  555. $multiplier = min(self::MULTIPLIER_MAX, (float) $row->multiplier + self::MULTIPLIER_STEP);
  556. } elseif ($last !== null && $last !== $taskDate) {
  557. $daysDiff = (int) Carbon::parse($taskDate)->diffInDays(Carbon::parse($last));
  558. if ($daysDiff > 1) {
  559. $multiplier = max(self::MULTIPLIER_MIN, (float) $row->multiplier - self::MULTIPLIER_STEP);
  560. $consecutive = 1;
  561. } else {
  562. $multiplier = (float) $row->multiplier;
  563. $consecutive = (int) $row->consecutive_days + 1;
  564. }
  565. }
  566. }
  567. DB::connection('write')->table(TableName::agent() . 'superball_user_multiplier')->updateOrInsert(
  568. ['user_id' => $userId],
  569. [
  570. 'consecutive_days' => $consecutive,
  571. 'last_task_date' => $taskDate,
  572. 'multiplier' => $multiplier,
  573. 'updated_at' => now()->format('Y-m-d H:i:s'),
  574. ]
  575. );
  576. }
  577. }