SuperballActivityService.php 33 KB

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